Reputation: 4349
Here's my data:
v x
0:0 96
0:0 119
0:0 108
1:0 73
1:0 65
2:0 83
2:0 73
2:0 23
How can I get the mean by groups of v i.e. the mean of x for all 0:0s, 1:0 etc.
My failed attempt:
df = read.csv(input.file.path, header=TRUE)
df$v <- as.factor(df$v)
ave(df$x, df$v)
Upvotes: 3
Views: 123
Reputation: 193687
ave
isn't the best option here. It will return a vector the same length as your inputs, while I'm guessing that you want to lump the results together into a more compact table.
If that's the case, try aggregate
or tapply
instead:
> aggregate(x ~ v, df, mean)
v x
1 0:0 107.66667
2 1:0 69.00000
3 2:0 59.66667
> tapply(df$x, df$v, mean)
0:0 1:0 2:0
107.66667 69.00000 59.66667
Upvotes: 6