目录
本文使用的例子皆为官方example,在Rstudio中使用 ?+函数名 即可查看。
1. melt:Melt an object into a form suitable for easy casting.
> head(tips)
total_bill tip sex smoker day time size
1 16.99 1.01 Female No Sun Dinner 2
2 10.34 1.66 Male No Sun Dinner 3
3 21.01 3.50 Male No Sun Dinner 3
4 23.68 3.31 Male No Sun Dinner 2
5 24.59 3.61 Female No Sun Dinner 4
6 25.29 4.71 Male No Sun Dinner 4
> head(melt(tips))
Using sex, smoker, day, time as id variables
sex smoker day time variable value
1 Female No Sun Dinner total_bill 16.99
2 Male No Sun Dinner total_bill 10.34
3 Male No Sun Dinner total_bill 21.01
4 Male No Sun Dinner total_bill 23.68
5 Female No Sun Dinner total_bill 24.59
6 Male No Sun Dinner total_bill 25.29
>
> head(airquality)
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
4 18 313 11.5 62 5 4
5 NA NA 14.3 56 5 5
6 28 NA 14.9 66 5 6
> names(airquality) <- tolower(names(airquality))
> head(melt(airquality, id=c("month", "day")))
month day variable value
1 5 1 ozone 41
2 5 2 ozone 36
3 5 3 ozone 12
4 5 4 ozone 18
5 5 5 ozone NA
6 5 6 ozone 28
>
> head(ChickWeight)
weight time chick diet
1 42 0 1 1
2 51 2 1 1
3 59 4 1 1
4 64 6 1 1
5 76 8 1 1
6 93 10 1 1
> names(ChickWeight) <- tolower(names(ChickWeight))
> head(melt(ChickWeight, id=2:4))
time chick diet variable value
1 0 1 1 weight 42
2 2 1 1 weight 51
3 4 1 1 weight 59
4 6 1 1 weight 64
5 8 1 1 weight 76
6 10 1 1 weight 93
2. cast:Cast a molten data frame into the reshaped or aggregated form you want
> names(airquality) <- tolower(names(airquality))
> aqm <- melt(airquality, id=c("month", "day"), na.rm=TRUE)
> head(aqm)
month day variable value
1 5 1 ozone 41
2 5 2 ozone 36
3 5 3 ozone 12
4 5 4 ozone 18
5 5 6 ozone 28
6 5 7 ozone 23
> str(cast(aqm, day ~ month ~ variable))
num [1:31, 1:5, 1:4] 41 36 12 18 NA 28 23 19