【问题标题】:Filtering by conditional values in R按 R 中的条件值过滤
【发布时间】:2020-10-01 21:23:13
【问题描述】:

所以,我的数据大致如下:

library(tidyverse)

id <- c(1, 1, 2, 2, 3, 3)
group <- c("A", "B", "A", "A", "B", "B")
value <- c(34, 12, 56, 78, 90, 91)

df <- tibble(id, group, value)
df

     id group value
  <dbl> <chr> <dbl>
1     1 A        34
2     1 B        12
3     2 A        56
4     2 A        78
5     3 B        90
6     3 B        91

我要做的可以描述为“对于每个id,取A组的最大值。但是,如果A不存在,则取B组的最大值。”所以我想要的输出看起来像:

     id group value
  <dbl> <chr> <dbl>
1     1 A        34
4     2 A        78
6     3 B        91

我尝试使用代码来做到这一点...

desired <- df %>%
  group_by(id) %>%
  filter(if (exists(group == "A")) max(value) else if (exists(group == "B")) (max(value)))

...但我收到了一个错误。帮忙?

【问题讨论】:

  • 一个data.table 选项:library(data.table); unique(setDT(df)[, .(value = max(value)), by=.(group, id)], by='id')

标签: r dplyr


【解决方案1】:

一个选项可能是:

df %>%
 group_by(id) %>%
 arrange(group, desc(value), .by_group = TRUE) %>%
 slice(which.max(group == "A"))

     id group value
  <dbl> <chr> <dbl>
1     1 A        34
2     2 A        78
3     3 B        91

【讨论】:

    【解决方案2】:

    这是一个基本的 R 选项

    subset(
      df[order(id, group, -value), ],
      ave(rep(TRUE, nrow(df)), id, FUN = function(x) seq_along(x) == 1)
    )
    

    给了

         id group value
      <dbl> <chr> <dbl>
    1     1 A        34
    2     2 A        78
    3     3 B        91
    

    基本思路是:

    • 我们通过df[order(id, group, -value), ] 重新排列df 的行
    • 然后我们在id重新排序的df中取第一个value

    【讨论】:

      【解决方案3】:

      使用data.table

      library(data.table)
      setDT(df)[order(id, group, -value), .SD[1], id]
      #    id group value
      #1:  1     A    34
      #2:  2     A    78
      #3:  3     B    91
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-30
        • 2022-09-22
        • 1970-01-01
        • 2015-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多