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