首页 > 解决方案 > 在 R 中使用 dplyr 按组计算平均值

问题描述

这是我的数据:

x <- rnorm(0,1, n = 6)
class <- c(1,1,1,2,2,2)
df <- cbind(x, class)

我想按类计算 x 的平均值并让它们对所有行重复(我得到一个新列,每个类的平均值重复,以便数据框的行数保持不变。

标签: rdplyrtidyverse

解决方案


我们可以用

library(dplyr)
df <- df %>%
    group_by(class) %>%
    mutate(Mean = mean(x)) %>%
    ungroup

-输出

df
# A tibble: 6 x 3
        x class    Mean
    <dbl> <dbl>   <dbl>
1  2.43       1  1.05  
2  0.0625     1  1.05  
3  0.669      1  1.05  
4  0.195      2 -0.0550
5  0.285      2 -0.0550
6 -0.644      2 -0.0550

数据

df <- data.frame(x, class)

推荐阅读