按组向原始数据添加一列均值 [英] Adding a column of means by group to original data
本文介绍了按组向原始数据添加一列均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据 R
data.frame
中的因子列添加一列均值.像这样:
I want to add a column of means based on factor column in R
data.frame
. Like this:
df1 <- data.frame(X = rep(x = LETTERS[1:2], each = 3), Y = 1:6)
df2 <- aggregate(data = df1, Y ~ X, FUN = mean)
df3 <- merge(x = df1, y = df2, by = "X", suffixes = c(".Old",".New"))
df3
# X Y.Old Y.New
# 1 A 1 2
# 2 A 2 2
# 3 A 3 2
# 4 B 4 5
# 5 B 5 5
# 6 B 6 5
为了解决这个问题,我必须创建两个不必要的data.frames
.我想知道一种通过因子列将平均值列附加到原始 data.frame
而不创建任何额外的 data.frames
的方法.感谢您的时间和帮助.
To accomplish this problem I've to create two unnecessary data.frames
. I'd like to know a way to append a column of means by factor column into my original data.frame
without creating any extra data.frames
. Thanks for your time and help.
推荐答案
这就是 ave
函数的用途.
This is what the ave
function is for.
df1$Y.New <- ave(df1$Y, df1$X)
这篇关于按组向原始数据添加一列均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文