【问题标题】:Filter using Dataset Position in R使用 R 中的数据集位置进行过滤
【发布时间】:2021-11-15 05:41:37
【问题描述】:

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

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

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

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

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

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

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

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

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

【问题讨论】:

标签: r dataframe filter dplyr dataset


【解决方案1】:

您可以使用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)
  )

【讨论】:

    【解决方案2】:

    if_all()if_any() 最近被引入到 tidyverse 中,用于过滤多个变量。

    library(dplyr)
    
    filter(retag, if_all(X:Y, ~ .x > 10 & .x < 35))
    
    # # A tibble: 5 x 2
    #       X     Y
    #   <int> <int>
    # 1    11    30
    # 2    12    31
    # 3    13    32
    # 4    14    33
    # 5    15    34
    
    filter(retag, if_any(X:Y, ~ .x == 2 | .x == 25))
    
    # # A tibble: 2 x 2
    #       X     Y
    #   <int> <int>
    # 1     2    21
    # 2     6    25
    
    

    数据

    retag <- structure(list(X = 1:20, Y = 20:39), row.names = c(NA, -20L), class = c("tbl_df", 
    "tbl", "data.frame"))
    

    【讨论】:

      【解决方案3】:

      这是一个基本的 R 选项。

      这将选择第 4 到 50 列中没有 8 且第 90 到 110 列中至少有一个 8 的行。

      result <- retag[rowSums(retag[4:50] == 8, na.rm = TRUE) == 0 & 
                      rowSums(retag[90:110] == 8,na.rm = TRUE) > 0, ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-22
        • 2015-11-03
        相关资源
        最近更新 更多