Sunday, July 13, 2014

make group (aggregate) data set in R

Suppose you have a data set called sort2013
And you want to calculate the group/aggregate of each Head_age

> sort2013
  Head_age P2_age P3_age P4_age P5_age P6_age P7_age P8_age
1       84     75      0      0      0      0      0      0
2       84     75      0      0      0      0      0      0
3       84     75      0      0      0      0      0      0
4       84     75      0      0      0      0      0      0
5       84     75      0      0      0      0      0      0
6       85     76      0      0      0      0      0      0
Etc...

Do the aggregate or grouping the data frame with aggregate()
> group2013 = aggregate(. ~ Head_age, sort2013, mean)
#aggregate or group of .(all column) ~(by) Head_age, in sort2013 data frame, and calculate the mean of all column. Then input into group2013 data frame

The result would be

> group2013
  Head_age   P2_age   P3_age   P4_age P5_age P6_age P7_age P8_age
1       16  0.00000 0.000000 0.000000      0      0      0      0
2       17  5.00000 0.000000 0.000000      0      0      0      0
3       18 13.44444 0.000000 0.000000      0      0      0      0
4       19 22.38095 7.000000 0.000000      0      0      0      0
5       20 17.45455 0.000000 0.000000      0      0      0      0
6       21 42.60000 6.666667 8.466667      0      0      0      0
Etc...


The result would be automatically sorted as you can see above

No comments:

Post a Comment