【问题标题】:Filter rows based on multiple conditions using dplyr使用 dplyr 基于多个条件过滤行
【发布时间】:2018-06-03 14:46:14
【问题描述】:
df <- data.frame(loc.id = rep(1:2,each = 10), threshold = rep(1:10,times = 2))

threshold >= 2 和threshold 对于每个loc.id >= 4 时,我想过滤掉第一行。我这样做了:

df %>% group_by(loc.id) %>% dplyr::filter(row_number() == which.max(threshold >= 2),row_number() == which.max(threshold >= 4))

我希望有这样的数据框:

      loc.id threshold
        1       2
        1       4
        2       2
        2       4

但它返回给我一个空数据框

【问题讨论】:

  • 你的问题不清楚
  • 我认为您可能需要将条件更改为 &gt;= 以获得预期的输出?

标签: r filter dplyr


【解决方案1】:

根据条件,我们可以slice连接两个which.max索引的行,得到unique(如果只有阈值大于4的情况,那么两个条件都得到相同的索引)

df %>%
    group_by(loc.id) %>%
    filter(any(threshold >= 2)) %>% # additional check
    #slice(unique(c(which.max(threshold > 2), which.max(threshold > 4))))
    # based on the expected output
    slice(unique(c(which.max(threshold >= 2), which.max(threshold >= 4))))
# A tibble: 4 x 2
# Groups:   loc.id [2]
#  loc.id threshold
#   <int>     <int>
#1      1         2
#2      1         4
#3      2         2
#4      2         4

请注意,可能存在阈值中没有大于或等于 2 的值的组。我们可以只保留这些组

【讨论】:

    【解决方案2】:

    如果这不是您想要的,请为下面的 df 分配一个名称并使用它来过滤您的数据集。

    df %>% 
      distinct() %>% 
      filter(threshold ==2 | threshold==4)
    #>   loc.id threshold
    #> 1      1         2
    #> 2      1         4
    #> 3      2         2
    #> 4      2         4
    ```
    

    【讨论】:

      猜你喜欢
      • 2022-07-21
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      • 1970-01-01
      • 2021-07-15
      • 2018-04-13
      • 1970-01-01
      相关资源
      最近更新 更多