如何旋转/取消旋转(铸造/熔化)数据框?
如何“取消透视”表格?正确的技术术语是什么?
更新:这个术语称为 melt
我有一个国家/地区数据框架和每年的数据
Country 2001 2002 2003
Nigeria 1 2 3
UK 2 NA 1
我想要类似的东西
Country Year Value
Nigeria 2001 1
Nigeria 2002 2
Nigeria 2003 3
UK 2001 2
UK 2002 NA
UK 2003 1
How can I 'unpivot' a table? What is the proper technical term for this?
UPDATE: The term is called melt
I have a data frame for countries and data for each year
Country 2001 2002 2003
Nigeria 1 2 3
UK 2 NA 1
And I want to have something like
Country Year Value
Nigeria 2001 1
Nigeria 2002 2
Nigeria 2003 3
UK 2001 2
UK 2002 NA
UK 2003 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我仍然不敢相信我用答案击败了安德里。 :)
I still can't believe I beat Andrie with an answer. :)
解决这个问题的基本 R
reshape
方法非常丑陋,特别是因为名称不是reshape
喜欢的形式。如下所示,第一行setNames
将列名称修改为reshape
可以使用的名称。基础 R 中更好的替代方案是使用 stack,如下所示:
现在还有用于重塑数据的新工具,例如“tidyr”包,它为我们提供了聚集功能。当然,
tidyr:::gather_.data.frame
方法只是调用reshape2::melt
,所以我的这部分答案不一定会增加太多,除了介绍您可能在 Hadleyverse 中遇到的较新语法。如果您想要问题中显示的行顺序,则此处的所有三个选项都需要对行进行重新排序。
第四个选项是使用我的“splitstackshape”包中的
merged.stack
。与基本 R 的reshape
一样,您需要将列名称修改为包含“变量”和“时间”指示符的名称。样本数据
The base R
reshape
approach for this problem is pretty ugly, particularly since the names aren't in a form thatreshape
likes. It would be something like the following, where the firstsetNames
line modifies the column names into something thatreshape
can make use of.A better alternative in base R is to use
stack
, like this:There are also new tools for reshaping data now available, like the "tidyr" package, which gives us
gather
. Of course, thetidyr:::gather_.data.frame
method just callsreshape2::melt
, so this part of my answer doesn't necessarily add much except introduce the newer syntax that you might be encountering in the Hadleyverse.All three options here would need reordering of rows if you want the row order you showed in your question.
A fourth option would be to use
merged.stack
from my "splitstackshape" package. Like base R'sreshape
, you'll need to modify the column names to something that includes a "variable" and "time" indicator.Sample data
您可以使用
reshape
包中的melt
命令。请参阅此处: http://www.statmethods.net/management/reshape.html可能类似于
melt(myframe, id=c('Country'))
You can use the
melt
command from thereshape
package. See here: http://www.statmethods.net/management/reshape.htmlProbably something like
melt(myframe, id=c('Country'))