如何重塑这些广泛的数据:(来自 csv 文件)
Name Code Indicator 1960 1961 1962
进入这种长格式?
Name Code Indicator Year
该reshape2
包很好地完成了这个功能melt
。
yourdata_melted <- melt(yourdata, id.vars=c('Name', 'Code', 'Indicator'), variable.name='Year')
这将添加一列value
您可以删除的列。yourdata_melted$value <- NULL
仅仅因为我喜欢继续使用基本 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
和tidyr
gather(test, "time", "value", 4:6)
数据
test <- data.frame(matrix(1:12,nrow=2))
names(test) <- c("name","code","indicator","1960","1961","1962")