【问题标题】:dplyr: Add group aggregates directly to long data frame [duplicate]dplyr:将组聚合直接添加到长数据框[重复]
【发布时间】:2014-07-22 10:24:56
【问题描述】:

是否可以在dplyr中的长格式原始数据框中直接添加组聚合?

到目前为止,我通过两个步骤来完成:聚合和合并。是否可以在dplyr 内且无需合并步骤?

library(dplyr)
df <- data.frame(x=rnorm(15), A=factor(rep(1:3, each=5)))
df2 <- df %>% group_by(A) %>% summarise(x_mean=mean(x))
df3 <- merge(df, df2, by="A")

结果:

> df3
   A      x x_mean
1  1  0.635 -0.077
2  1 -1.059 -0.077
3  1  0.408 -0.077
4  1  1.404 -0.077
5  1 -1.774 -0.077
6  2 -0.419 -0.256
7  2  0.417 -0.256
8  2 -0.443 -0.256
9  2 -0.431 -0.256
10 2 -0.403 -0.256
11 3  0.239  0.767
12 3  1.060  0.767
13 3  1.633  0.767
14 3  0.265  0.767
15 3  0.640  0.767

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    我想你想要mutate 而不是summarise:

    df %>% group_by(A) %>% mutate(x_mean=mean(x))
    

    附带说明,这是基本 R 解决方案非常简单的情况之一:

    ave(df$x,df$A)
    

    【讨论】:

      猜你喜欢
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-17
      • 2017-09-29
      • 2016-10-31
      • 1970-01-01
      相关资源
      最近更新 更多