我遇到了与 How to aggregate some columns while keeping other columns in R? 所述类似的问题,但我尝试过的解决方案都没有工作。
我有一个这样的数据框:
df<-data.frame(a=rep(c("a","b"),each=2),b=c(500,400,200,300),
c = c(5,10,2,4),stringsAsFactors = FALSE)
> df
a b c
1 a 500 5
2 a 400 10
3 b 200 2
4 b 300 4
df%>%
group_by(a)%>%
summarise('max' = max(c), 'sum'=sum(c))
a max sum
<chr> <dbl> <dbl>
1 a 10 15
2 b 4 6
but I need also column b:
1 a 10 15 400
2 b 4 6 300
b 列的值为 max(c)。
编辑特定案例的数据:
> df
a b c
1 a 500 5
2 a 400 5
在这种情况下,我需要在摘要中设置更高的值 col b
# a max sum b
# <chr> <dbl> <dbl> <dbl>
# 1 a 5 10 500
最佳答案
我会将 summarise
替换为 mutate
(保留所有行),然后过滤您想要的行。然后 tibble 仍然被分组,因此需要一个 ungroup
来摆脱这些组。
d f%>%
group_by(a) %>%
mutate('max' = max(c), 'sum'=sum(c)) %>%
filter(c == max) %>%
ungroup()
# a b c max sum
# <chr> <dbl> <dbl> <dbl> <dbl>
# 1 a 400 10 10 15
# 2 b 300 4 4 6
关于r - 使用 dplyr 时如何保留其他列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60929907/