## Loading required package: grid
1 reshape
1.1 熔化
Melt的用法是 melt(data, id = c(“cut”, “color”, “clarity”))。下面使用reshape2中的airquality数据来演示。其结果如下
• 前n行是id (具体列数,依据id里有几项,如“cut”, “color”, “clarity” 三项)
• next列是variable
• 最后是value
## ozone solar.r wind temp month day
## 1 41 190 7.4 67 5 1
## 2 36 118 8.0 72 5 2
## 3 12 149 12.6 74 5 3
## month day variable value
## 1 5 1 ozone 41
## 2 5 2 ozone 36
## 3 5 3 ozone 12
## month day variable value
## 610 9 28 temp 75
## 611 9 29 temp 76
## 612 9 30 temp 68
1.2 锻造
cast时,reshape2中有acast和dcast。acast可以cast 多维,当然也包括2维。但是与dcast相比,acast在cast二维dataframe时,少了第一列(也就是行名)。
• id ~variable:一个或是多个id vs variable。若是多个id vs variable,要用acast,因为结果是多维
dcast(aqm, month ~ variable, mean)
## month ozone solar.r wind temp
## 1 5 23.62 181.3 11.623 65.55
## 2 6 29.44 190.2 10.267 79.10
## 3 7 59.12 216.5 8.942 83.90
## 4 8 59.96 171.9 8.794 83.97
## 5 9 31.45 167.4 10.180 76.90
dcast(aqm, month ~ variable, mean, margins = TRUE)
## month ozone solar.r wind temp (all)
## 1 5 23.62 181.3 11.623 65.55 68.71
## 2 6 29.44 190.2 10.267 79.10 87.38
## 3 7 59.12 216.5 8.942 83.90 93.50
## 4 8 59.96 171.9 8.794 83.97 79.71
## 5 9 31.45 167.4 10.180 76.90 71.83
## 6 (all) 42.13 185.9 9.958 77.88 80.06
#Need to load ply package to use .() function to subset
dcast(aqm, month ~ variable, mean, subset = .(variable == "ozone"))
## month ozone
## 1 5 23.62
## 2 6 29.44
## 3 7 59.12
## 4 8 59.96
## 5 9 31.45
# Switch Row and Column
dcast(aqm, variable ~ month, mean)
## variable 5 6 7 8 9
## 1 ozone 23.62 29.44 59.115 59.962 31.45
## 2 solar.r 181.30 190.17 216.484 171.857 167.43
## 3 wind 11.62 10.27 8.942 8.794 10.18
## 4 temp 65.55 79.10 83.903 83.968 76.90
dcast(aqm, variable ~ month, mean, subset = .(month == 5))
## variable 5
## 1 ozone 23.62
## 2 solar.r 181.30
## 3 wind 11.62
## 4 temp 65.55