KT_1
KT_1

Reputation: 8484

Group mean by another variable in R

For a sample dataframe:

set.seed (1000)
value <- rnorm(1000)
wave <- rep(1:5, times=20, each=10)
length <- rep(1:10, times=10, each=10)
df <- data.frame(value, length, wave)

I want to create a summary table for the mean for each length (1-10) by each 'wave'. If I just had data from one time point, I would use:

aggregate(df$value, by=list(Category=df$length), FUN=sum)

But how do I calculate this for all my different waves? Can I do this in one command?

Upvotes: 0

Views: 38

Answers (1)

Jilber Urbina
Jilber Urbina

Reputation: 61154

Do you mean something like this...:

> aggregate(value~length+wave, data=df, FUN=sum)
   length wave      value
1       1    1 -14.055504
2       6    1 -11.303317
3       2    2 -24.260527
4       7    2   4.307751
5       3    3  -2.128476
6       8    3  11.522721
7       4    4  -1.202818
8       9    4  20.985253
9       5    5  12.848358
10     10    5  -9.189343

Upvotes: 1

Related Questions