重新整形data.frame从宽到长格式 [英] Reshaping data.frame from wide to long format
问题描述
我有一些麻烦,将我的 data.frame
从宽表转换为长表。
目前看起来像这样:
wide< - read.table(textConnection(
pre>
代码国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),标题=真)
哪些产生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 longdata.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 astidyr::gather()
anddata.table::melt()
solutions and the olderreshape::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 asmelt
/cast
. Here is a solution with reshape, assuming your data frame id calledd
: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屋!