【发布时间】:2021-09-27 20:30:21
【问题描述】:
我有一个包含 4 列 Age、Location、Distance 和 Value 的数据框。 Age 和 Location 每个都有两个可能的值,而 Distance 可以有三个。 Value 是观察到的连续变量,每个 Distance 测量了 3 次。
考虑到Age 和Location,我想计算其中一个Distance 值的平均值,然后在组合其他两个Distance 时计算另一个平均值Value。我试图回答,Distance 0.5 相对于 Distance 1.5 和 2.5 对于每个 Age 和 Location 的平均值是什么?
如何使用 dplyr 做到这一点?
示例数据
library(dyplyr)
set.seed(123)
df1 <- data.frame(matrix(ncol = 4, nrow = 36))
x <- c("Age","Location","Distance","Value")
colnames(df1) <- x
df1$Age <- rep(c(1,2), each = 18)
df1$Location <- as.character(rep(c("Central","North"), each = 9))
df1$Distance <- rep(c(0.5,1.5,2.5), each = 3)
df1$Value <- round(rnorm(36,200,25),0)
输出应该是这样的
Age Location Mean_0.5 Mean_1.5_and_2.5
1 1 Central 206 202
2 1 North 210 201
3 2 Central 193 186
4 2 North 202 214
【问题讨论】: