Alex Rivera | Logout

Adding a column of means by group to original data

Asked 2011-11-02T05:03:30.920
25

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

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.

Edit
Report

1 Answer

8

ddply and transform to the rescue (although I'm sure you'll get at least 4 different ways to do this):

library(plyr)
ddply(df1,.(X),transform,Y.New = mean(Y))
  X Y 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
answered 2011-11-02T05:08:40.557

Your Answer