重塑数据从宽到长?

时间:2012-12-13 20:15:15

标签: r

如何重塑这些广泛的数据:(来自csv文件)

Name    Code    Indicator     1960    1961    1962  

进入这种长格式?

Name    Code    Indicator     Year

2 个答案:

答案 0 :(得分:7)

reshape2包与函数melt很好地协同工作。

yourdata_melted <- melt(yourdata, id.vars=c('Name', 'Code', 'Indicator'), variable.name='Year')

这会添加一列value,您可以删除。 yourdata_melted$value <- NULL

答案 1 :(得分:5)

只是因为我想继续使用基本R功能的广告系列:

测试数据:

test <- data.frame(matrix(1:12,nrow=2))
names(test) <- c("name","code","indicator","1960","1961","1962")
test

  name code indicator 1960 1961 1962
1    1    3         5    7    9   11
2    2    4         6    8   10   12

现在重塑它!

reshape(
   test,
   idvar=c("name","code","indicator"),
   varying=c("1960","1961","1962"),
   timevar="year",
   v.names="value",
   times=c("1960","1961","1962"),
   direction="long"
)

#           name code indicator year value
#1.3.5.1960    1    3         5 1960     7
#2.4.6.1960    2    4         6 1960     8
#1.3.5.1961    1    3         5 1961     9
#2.4.6.1961    2    4         6 1961    10
#1.3.5.1962    1    3         5 1962    11
#2.4.6.1962    2    4         6 1962    12