我想计算组均值,但将它们保存为原始数据旁边的向量。有没有一种有效的方法在dplyr
中执行此操作?
原始data.frame
:
dat <- data.frame(
group = c("A","A","A","B","B","B"),
value = c(4, 5, 6, 7, 8, 9)
)
> dat
group value
1 A 4
2 A 5
3 A 6
4 B 7
5 B 8
6 B 9
所需的data.frame
具有完整的组矢量意味着:
dat2 <- data.frame(
group = c("A","A","A","B","B","B"),
value = c(4, 5, 6, 7, 8, 9),
groupmeanvalue = c(5, 5, 5, 8, 8, 8)
)
> dat2
group value groupmeanvalue
1 A 4 5
2 A 5 5
3 A 6 5
4 B 7 8
5 B 8 8
6 B 9 8
答案 0 :(得分:0)
dat <- dat %>%
group_by(group) %>%
mutate(groupmeanvalue = mean(value))
dat
Source: local data frame [6 x 3]
Groups: group [2]
group value groupmeanvalue
(fctr) (dbl) (dbl)
1 A 4 5
2 A 5 5
3 A 6 5
4 B 7 8
5 B 8 8
6 B 9 8
答案 1 :(得分:0)
我们可以使用ave
base R
dat$groupmeanvalue <- with(dat, ave(value, group))
dat$groupmeanvalue
#[1] 5 5 5 8 8 8
或data.table
library(data.table)
setDT(dat)[, groupmeanvalue := mean(value), by = group]