您可以拥有宽格式或长格式的数据。这是非常重要的事情,因为可用的方法不同,具体取决于格式。我知道你必须使用reshape 包melt()并cast()从 reshape 包中工作,但似乎有些东西我没有得到。
有人可以给我一个简短的概述,你是如何做到这一点的?
您可以拥有宽格式或长格式的数据。这是非常重要的事情,因为可用的方法不同,具体取决于格式。我知道你必须使用reshape 包melt()并cast()从 reshape 包中工作,但似乎有些东西我没有得到。
有人可以给我一个简短的概述,你是如何做到这一点的?
在 Hadley Wickham 的网站上有几个资源包(现在称为reshape2),其中包括Journal of Statistical Software 中关于该包的论文的链接。
这是论文中的一个简短示例:
> require(reshape2)
Loading required package: reshape2
> data(smiths)
> smiths
     subject time age weight height
1 John Smith    1  33     90   1.87
2 Mary Smith    1  NA     NA   1.54
我们注意到数据是宽格式的。要进入长格式,我们将smiths数据框熔化:
> melt(smiths)
Using subject as id variables
     subject variable value
1 John Smith     time  1.00
2 Mary Smith     time  1.00
3 John Smith      age 33.00
4 Mary Smith      age    NA
5 John Smith   weight 90.00
6 Mary Smith   weight    NA
7 John Smith   height  1.87
8 Mary Smith   height  1.54
请注意如何melt()选择其中一个变量作为 id,但我们可以通过参数明确说明要使用的变量'id':
> melt(smiths, id = "subject")
     subject variable value
1 John Smith     time  1.00
2 Mary Smith     time  1.00
3 John Smith      age 33.00
4 Mary Smith      age    NA
5 John Smith   weight 90.00
6 Mary Smith   weight    NA
7 John Smith   height  1.87
8 Mary Smith   height  1.54
这是另一个示例?cast:
#Air quality example
names(airquality) <- tolower(names(airquality))
aqm <- melt(airquality, id=c("month", "day"), na.rm=TRUE)
如果我们存储熔化的数据帧,我们可以转换成其他形式。在reshape(称为reshape2)的新版本中,有函数acast()并分别dcast()返回类似数组的(数组、矩阵、向量)结果或数据框。这些函数还采用聚合函数(例如mean())来提供熔融形式的数据摘要。例如,根据上面的空气质量示例,我们可以为数据集中的变量生成广义的月平均值:
> dcast(aqm, month ~ variable, mean)
  month    ozone  solar.r      wind     temp
1     5 23.61538 181.2963 11.622581 65.54839
2     6 29.44444 190.1667 10.266667 79.10000
3     7 59.11538 216.4839  8.941935 83.90323
4     8 59.96154 171.8571  8.793548 83.96774
5     9 31.44828 167.4333 10.180000 76.90000
reshape2:melt()和配对acast()中实际上只有两个主要功能。dcast()查看这两个函数的帮助页面中的示例,查看 Hadley 的网站(上面的链接)并查看我提到的论文。那应该让你开始。
你也可以看看 Hadley 的plyr包,它做类似的事情,reshape2但设计做更多的事情。
您不必使用meltand cast。  
重塑数据可以通过多种方式完成。在您引用的特定示例中,使用recastwithaggregate是多余的,因为aggregate任务本身就可以完成。
aggregate(cbind(LPMVTUZ, LPMVTVC, LPMVTXC) ~ year, dtm, sum)
# or even briefer by first removing the columns you don't want to use
aggregate(. ~ year, dtm[,-2], sum)
我确实喜欢在您的博客文章中如何解释melt正在做什么。很少有人理解这一点,一旦你看到它,就会更容易看到它是如何cast工作的,以及如果你愿意的话,你可以如何编写自己的函数。
请参阅reshape2 维基。正如您所料,它肯定会提供更多示例。