首页 > 解决方案 > 使用 R 中的数据集位置进行过滤

问题描述

我不太熟悉 R 中的 dplyr 函数。但是,我想将我的数据集过滤到某些条件下。

假设我的数据集中有 100 多个属性。我想执行具有多个条件的过滤器。

我可以将我的编码过滤器放在列的位置而不是它们的名称,如下所示:

y = filter(retag, c(4:50) != 8 & c(90:110) == 8)

我已经尝试过几次类似的编码,但仍然没有得到结果。

我也尝试过如下编码,但不确定如何在 rowSums 函数中添加其他条件。

retag[rowSums((retag!=8)[,c(4:50)])>=1,]

我发现的唯一示例是使用数据集名称而不是位置。

或者有什么方法可以使用数据集位置进行过滤,因为我的数据非常庞大。

标签: rdataframefilterdplyrdataset

解决方案


您可以使用filter()和的组合across()。我没有您的数据框版本,retag所以我创建了自己的数据框作为示例

set.seed(2000)

retag <- tibble(
  col1 = runif(n = 1000, min = 0, max = 10) %>% round(0),
  col2 = runif(n = 1000, min = 0, max = 10) %>% round(0),
  col3 = runif(n = 1000, min = 0, max = 10) %>% round(0),
  col4 = runif(n = 1000, min = 0, max = 10) %>% round(0),
  col5 = runif(n = 1000, min = 0, max = 10) %>% round(0)
)

# filter where the first, second, and third column all equal 5 and the fourth column does not equal 5
retag %>%
  filter(
    across(1:3, function(x) x == 5), 
    across(4, function(x) x != 5)
  )

推荐阅读