在R中使用dplyr按组计算平均值

时间:2021-07-14 20:43:42

标签: r dplyr tidyverse

这是我的数据:

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

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

2 个答案:

答案 0 :(得分:3)

我们可以使用

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)

答案 1 :(得分:1)

使用 ave 的基本 R 选项

transform(
    df,
    Mean = ave(x, class)
)
相关问题