如何在 R 面板中转换工作表?

问题描述 投票:0回答:1

下面是我的数据库的一个小样本。

example

如您所见,有两个单位(3100104 和 3100203)和一个数值变量 X,假设值为 2010 年和 2011 年。

问题是我需要使用 R 将其转换为面板格式。应该如下图所示:

enter image description here

如有任何帮助,我们将不胜感激。

示例数据:

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")
r panel panel-data
1个回答
0
投票

从宽到长重塑形状,然后转置:

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
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.