将最大值应用于整个组

时间:2016-11-28 18:13:24

标签: r group-by max

我有这样的df:

Id   count
1      0
1      5
1      7
2      5
2      10
3      2
3      5
3      4

我希望获得最大数量并根据ID将其应用于整个“组”,如下所示:

Id   count   max_count
1      0        7
1      5        7
1      7        7
2      5        10
2      10       10
3      2        5
3      5        5
3      4        5

我已经尝试了pmax,slice等。我通常无法处理特定于区间的数据;如果你能指引我使用非常适合这类数据的工具,我真的很感激!

1 个答案:

答案 0 :(得分:1)

在Gavin Simpson的帮助下计算出来:Aggregate a dataframe on a given column and display another column

maxcount <- aggregate(count ~ Id, data = df, FUN = max)

new_df<-merge(df, maxcount)

更好的方式:

df$max_count <- with(df, ave(count, Id, FUN = max))
相关问题