将 data.frame 从宽格式重塑为长格式 [英] Reshaping data.frame from wide to long format
问题描述
将我的 data.frame
从宽表转换为长表时遇到了一些麻烦.目前它看起来像这样:
I have some trouble to convert my data.frame
from a wide table to a long table.
At the moment it looks 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
现在我想把这个 data.frame
转换成一个长的 data.frame
.像这样的:
Now I would like to transform this data.frame
into a long data.frame
.
Something like this:
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
我已经查看并尝试过使用 melt()
和 reshape()
函数正如一些人在类似问题中所建议的那样.但是,到目前为止,我只得到了混乱的结果.
I have looked at and already tried using the melt()
and the reshape()
functions
as some people were suggesting in similar questions.
However, so far I only get messy results.
如果可能的话,我想用 reshape()
函数来做,因为它看起来更好处理一些.
If it is possible I would like to do it with the reshape()
function since
it looks a little bit nicer to handle.
推荐答案
reshape()
需要一段时间来适应,就像 melt
/cast代码>.这是一个重塑的解决方案,假设您的数据框称为
d
:
reshape()
takes a while to get used to, just as melt
/cast
. Here is a solution with reshape, assuming your data frame is 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屋!