在《R语言实战》这本书中,第七章介绍了通过reshape包分组计算概述统计量的方法,代码如下:
- library(reshape)
- dstats <- function(x)(c(n=length(x), mean=mean(x), sd=sd(x)))
- dfm <- melt(mtcars, measure.vars=c("mpg", "hp", "wt", id.vars=c("am", "cyl"))
- cast(dfm, am + cyl + variable~ ., dstats)
复制代码若用reshape2包做同样的工作,则会产生错误,代码如下:
- library(reshape2)
- dstats<-function(x)(c(n=length(x), mean=mean(x), sd=sd(x)))
- dfm<-melt(mtcars, measure.vars=c("mpg", "hp", "wt"),id.vars=c("am", "cyl"))
- dcast(dfm, am + cyl + variable ~., dstats)
复制代码会产生如下错误提示:
- Error in structure(ordered, dim = ns) :
- dims [product 18] do not match the length of object [54]
复制代码区别在于reshape2包中没有cast()函数,而是替代为acast()或dcast(),问题来了,reshape包的cast()函数与reshape2包的dcast()函数有何区别,问题在哪?