I want to get mean of var1 and var2 by group low and high. How can I get mean of two variables each by group (low and high) ?
ID var1 var2 low high
1 1 6 0 1
2 2 7 0 1
3 3 8 1 0
4 4 9 1 0
5 5 10 0 1
aggregate
does what you need, given the proper input.To get the aggregate of multiple columns, you can
cbind
them so that they are separate columns in the result:If you want to take the mean of every column other than
low
andhigh
,.
is handy, meaning "all other columns":Note that
+
has a special meaning in the formula if it is on the right side of the~
. It doesn't mean a sum, but it means using both factors. On the left side, it means addition.For individual variables, tapply is also very convenient, especially if multiple groups are there:
A
dplyr
solution:which gives you:
as Richard Scriven points out, you might be talking about the sum of var 1 and var 2 that you want to mean, in which case:
Here is an option using
data.table
and for the second case