reshape2,主要用于宽数据和长数据之间的转换。
主要就是melt
和*cast
函数的应用。
具体可参考如下图片
参考的r代码如下
代码语言:javascript复制names(airquality) = tolower(names(airquality))
head(airquality)
# melt
md = melt(airquality,id= c("month","day"))
md = melt(airquality,id = c("month","day"),variable.name = "climate_variable",
value.name = "climate_value",na.rm=T)
head(md)
head(airquality)
dim(airquality)
dim(md)
# cast to data.frame
# restore original data
cd = dcast(md,month day~climate_variable,value.var = "climate_value")
head(cd)
head(airquality)
dim(cd)
dim(airquality)
# aggregate by month to get the mean value
dcast(md,month~climate_variable,value.var = "climate_value",fun.aggregate = mean,
na.rm=T)
# add margin
dcast(md,month~climate_variable,value.var = "climate_value",fun.aggregate = mean,
na.rm=T, margins=c("month","climate_variable") )
# use of ...
dcast(md,month day~...)
# use of .
dcast(md,month~.)
table(md$month)
# with plyr
library(plyr)
acast(md,climate_variable~month,mean,subset=.(climate_variable == "solar.r"))