【问题标题】:Deleting rows based upon meeting multiple column conditions in R根据满足R中的多列条件删除行
【发布时间】:2020-06-10 21:00:04
【问题描述】:

我有一个非常大的数据集,我想通过删除我选择的列满足这些列选择中的所有条目都等于 0 的条件的行来清理。这是我目前拥有的:

df1 <- filter(df,((n)==0 & (n+1)==0 & (n+2)==0 & (n+3)==0 & ......(n+100)==0)

如何执行此操作,以便删除每第 n 列满足此条件的所有行条目?

另外,如果我想迭代这个条件,我需要说明列的名称吗?

这是一个示例数据集:

 A tibble: 10 x 10
 A B C D E F G H I J
 1 1 1 1 1 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0
 0 0 1 1 1 0 0 0 1 1
 0 0 0 0 0 0 0 0 0 0
 1 1 1 1 1 1 1 0 1 1
 1 1 1 1 1 0 0 0 0 0 
 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 1 0 0
 0 0 0 0 1 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0

我想删除 F、G 和 H 列等于 0 的所有行,我的结果将是:

 A tibble: 10 x 2
 A B C D E F G H I J
 1 1 1 1 1 1 1 0 1 1
 0 0 0 0 0 0 0 1 0 0

【问题讨论】:

  • 您的问题不可重现。请更新一个小例子(就像我的帖子一样)以便我可以测试它。
  • 这不是n &lt;- 5; df %&gt;% filter_at(n:(n+100), any_vars(. != 0))

标签: r dataframe data-wrangling


【解决方案1】:

一个选项是filter_at

library(dplyr)
df %>%
   filter_at(11:20, any_vars( .  != 0))

一个可重现的例子

df1 %>% 
   filter_at(vars(`11`:`13`), any_vars(. != 0))
# A tibble: 2 x 4
#   `11`  `12`  `13` grp  
#     <dbl> <dbl> <dbl> <chr>
#1     1     0     4 a    
#2     0     1     0 b    

或使用devel 版本的dplyr 中的across

df1 %>%
    filter(across(cols = matches('^\\d+$'), ~ (.x == 0))) %>% 
    anti_join(df1, .)
# A tibble: 2 x 4
#   `11`  `12`  `13` grp  
#  <dbl> <dbl> <dbl> <chr>
#1     1     0     4 a    
#2     0     1     0 b    

更新

根据 OP 的更新,如果我们将“n”作为某个列索引并希望根据该位置的列过滤到之后的 100 列

n <- 5
df %>%
     filter_at(n:(n+100), any_vars(. != 0))

更新2

df2 %>%
   filter_at(vars(F, G, H), any_vars(. != 0))
# A tibble: 2 x 10
#      A     B     C     D     E     F     G     H     I     J
#  <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
#1     1     1     1     1     1     1     1     0     1     1
#2     0     0     0     0     0     0     0     1     0     0

或使用base R

df2[rowSums(df2[c("F", "G", "H")] != 0) > 0,]

数据

df1 <- tibble(`11` = c(1, 0, 0), `12` = c(0, 1, 0), `13` = c(4,  0, 0), 
  grp = letters[1:3])





df2 <- structure(list(A = c(1L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L), 
    B = c(1L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L), C = c(1L, 
    0L, 1L, 0L, 1L, 1L, 0L, 0L, 0L, 0L), D = c(1L, 0L, 1L, 0L, 
    1L, 1L, 0L, 0L, 0L, 0L), E = c(1L, 0L, 1L, 0L, 1L, 1L, 0L, 
    0L, 1L, 0L), F = c(0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L
    ), G = c(0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L), H = c(0L, 
    0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L), I = c(0L, 0L, 1L, 0L, 
    1L, 0L, 0L, 0L, 0L, 0L), J = c(0L, 0L, 1L, 0L, 1L, 0L, 0L, 
    0L, 0L, 0L)), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

【讨论】:

  • 当我执行此方法时,我收到一条错误消息,内容为:useMethod("tbl_vars").. 没有适用于对象或类的适用方法
  • @richierich 我猜您正在尝试删除那些已删除所有 0 的列的行,对吧。在这种情况下,更新的示例对我有用
  • 对不起,我的问题写的不好,请看我的更新
  • 再次更新以增加清晰度
  • @richierich 请检查我的更新2。该代码对我来说工作正常
猜你喜欢
  • 2019-06-24
  • 2020-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多