Translate

Wednesday, 22 July 2015

reshape2 package - similar function to pivot table in Excel


recast() in "reshape2" package offers a function that can work like a pivot table in Excel.



library(reshape2)
recast(data = CO2, Plant + Type ~ Treatment, measure.var = "uptake", sum)
   Plant        Type nonchilled chilled
1    Qn1      Quebec      232.6     0.0
2    Qn2      Quebec      246.1     0.0
3    Qn3      Quebec      263.3     0.0
4    Qc1      Quebec        0.0   209.8
5    Qc3      Quebec        0.0   228.1
6    Qc2      Quebec        0.0   228.9
7    Mn3 Mississippi      168.8     0.0
8    Mn2 Mississippi      191.4     0.0
9    Mn1 Mississippi      184.8     0.0
10   Mc2 Mississippi        0.0    85.0
11   Mc3 Mississippi        0.0   121.1
12   Mc1 Mississippi        0.0   126.0


Sometimes, the variables need to be treated as vector.

recast(data=CO2, CO2$Plant + CO2$Type ~ CO2$Treatment, measure.var = "uptake", sum)

No comments:

Post a Comment