0

I have a question on assigning group means to an R data.frame. I know that we can calculate group means using tapply.

Example: Group mean by Species.

(mean.SL = tapply(iris[,1],iris[5],mean))
# Species
#     setosa versicolor  virginica 
#      5.006      5.936      6.588 

How do I assign these group means back to the same data.frame? For example, I would like the following result. I appreciate any help you can provide.

     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species mean.SL
  1           5.1         3.5          1.4         0.2     setosa   5.006
  2           4.9         3.0          1.4         0.2     setosa   5.006
 ..
 ..
 51           7.0         3.2          4.7         1.4 versicolor   5.936
 52           6.4         3.2          4.5         1.5 versicolor   5.936
 ..
 ..
101           6.3         3.3          6.0         2.5  virginica   6.588
102           5.8         2.7          5.1         1.9  virginica   6.588
  • 1
    The question would be a better fit at Stack overflow since the focus is on how to program - rather than a clear cut statistics question. – Repmat Feb 14 '16 at 18:37
  • Thank you Repmat. Sorry for posting it too early. Soon after posting, I got the answer using R package ddply. –  Feb 14 '16 at 18:46

1 Answers1

0

You can use ave:

transform(iris, mean.SL = ave(Sepal.Length, Species))
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168