'Mean by groups by multiple columns in r
I have the next dataframe
obs1 obs2 obs3 zone
1 0 1 Rural
1 1 1 Rural
0 1 1 Urban
1 0 0 Urban
0 1 0 Rural
I am trying to get something like this
Mean Rural 0.6666
Mean Urban 0.5
Is that possible?
Solution 1:[1]
You can try:
aggregate(values ~ zone, cbind(stack(df[-4]), df[4]), mean)
zone values
1 Rural 0.6666667
2 Urban 0.5000000
Or (assuming no missing values):
tapply(rowMeans(df[-4]), df[4], mean)
Rural Urban
0.6666667 0.5000000
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |