下面是我的数据库的一个小样本。
如您所见,有两个单位(3100104 和 3100203)和一个数值变量 X,假设值为 2010 年和 2011 年。
问题是我需要使用 R 将其转换为面板格式。应该如下图所示:
如有任何帮助,我们将不胜感激。
示例数据:
y <- structure(list(a = 1:3, b = 5:7, c=8:10), .Names = c("ID", "X_2010","X_2011"), row.names = c(NA, -3L), class = "data.frame")
从宽到长重塑形状,然后转置:
library(data.table)
# convert to data.table
setDT(y)
# reshape wide to long
res <- melt(y, id.vars = "ID", variable.name = "Year", value.name = "X")
# remove X from year
res[, Year := as.integer(gsub("X_", "", Year, fixed = TRUE)) ]
# transpose
as.data.frame(t(res))
# V1 V2 V3 V4 V5 V6
# ID 1 2 3 1 2 3
# Year 2010 2010 2010 2011 2011 2011
# X 5 6 7 8 9 10