r - 在 R 中使用 dplyr 按组计算平均值
问题描述
这是我的数据:
x <- rnorm(0,1, n = 6)
class <- c(1,1,1,2,2,2)
df <- cbind(x, class)
我想按类计算 x 的平均值并让它们对所有行重复(我得到一个新列,每个类的平均值重复,以便数据框的行数保持不变。
解决方案
我们可以用
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)
推荐阅读
- java - 有没有办法通过Java Springboot在mysql中设置会话特定的系统变量?
- python - 如何为基于 CLI 的应用程序编写可安装的 python 包
- ansible - ansible重新启动机器时如何向用户显示消息
- java - 如何配置 DBeaver 以显示我的架构?
- python - 对相似类型的测试进行参数化
- javascript - 访问 locaStorage 中的另一个环境
- design-patterns - 以数据库为中心的架构与疲惫的架构
- csv - gocsv UnmarshalBytes 失败
- cluster-analysis - 使用节点的属性进行聚类
- angular - 冻结列并用 PrimeNG 包装 - 行高混杂