【发布时间】: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')