重新整形data.frame从宽到长格式 [英] Reshaping data.frame from wide to long format

查看:102
本文介绍了重新整形data.frame从宽到长格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些麻烦,将我的 data.frame 从宽表转换为长表。
目前看起来像这样:

  wide<  -  read.table(textConnection(
代码国1950年1951 1952 1953 1954
阿富汗阿富汗20,249 21,352 22,532 23,557 24,555
阿尔巴尼亚8,097 8,986 10,058 11,123 12,246),标题=真)
pre>

哪些产生data.frame wide 如下所示:

 代码国家1950 1951 1952 1953 1954 
AFG阿富汗20,249 21,352 22,532 23,557 24,555
ALB阿尔巴尼亚8,097 8,986 10,058 11,123 12,246

我想将 wide 转换成长数据。框架例如:

 代码国家年度值
AFG阿富汗1950 20,249
阿富汗阿富汗1951 21,352
阿富汗阿富汗1952年22,532美元b $ b阿富汗阿富汗1953年23,557美元b $ b阿富汗阿富汗1954年24,555美元b $ b阿尔巴尼亚1950 8,097
ALB阿尔巴尼亚1951 8,986
ALB阿尔巴尼亚1952 10,058
ALB阿尔巴尼亚1953 11,123
ALB阿尔巴尼亚1954 12,246

截至2016年,选项包括 reshape2 :: melt(),以及 tidyr解决方案和旧版本的 reshape :: reshape() 函数。然而,到目前为止,我只会收到混乱的结果,尝试使用这些多个类似但不同的功能。



如果可能,我想用 reshape()函数,因为
看起来有点更好处理,但使用其他包的例子/理由赞赏。

解决方案

reshape()需要一段时间才能习惯,就像融合 / cast 。这是一个重塑的解决方案,假设您的数据框架ID称为 d

  reshape(d,direction =long,vary = list(name(d)[3:7]),v.names =Value,
idvar = c(Code ),timevar =Year,times = 1950:1954)


I have some trouble to convert my data.frame from a wide table to a long table. At the moment it looks like this:

wide <- read.table(textConnection(
"Code Country        1950    1951    1952    1953    1954
AFG  Afghanistan    20,249  21,352  22,532  23,557  24,555
ALB  Albania        8,097   8,986   10,058  11,123  12,246"), header=TRUE)

Which yields data.frame wide looking like this:

Code Country        1950    1951    1952    1953    1954
AFG  Afghanistan    20,249  21,352  22,532  23,557  24,555
ALB  Albania        8,097   8,986   10,058  11,123  12,246

I want to transform wide into a long data.frame e.g:

Code Country        Year    Value
AFG  Afghanistan    1950    20,249
AFG  Afghanistan    1951    21,352
AFG  Afghanistan    1952    22,532
AFG  Afghanistan    1953    23,557
AFG  Afghanistan    1954    24,555
ALB  Albania        1950    8,097
ALB  Albania        1951    8,986
ALB  Albania        1952    10,058
ALB  Albania        1953    11,123
ALB  Albania        1954    12,246

As of 2016, options include reshape2::melt(), as well as tidyr::gather() and data.table::melt() solutions and the older reshape::reshape() function. However, so far I only get messy results trying to use these multiple similar-but-different functions.

If it is possible I would like to do it with the reshape() function since it looks a little bit nicer to handle, but examples/rationales for using other packages appreciated.

解决方案

reshape() takes a while to get used to, just as melt/cast. Here is a solution with reshape, assuming your data frame id called d:

reshape(d, direction="long", varying=list(names(d)[3:7]), v.names="Value", 
        idvar=c("Code","Country"), timevar="Year", times=1950:1954)

这篇关于重新整形data.frame从宽到长格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆