将面板数据宽格式 reshape 为长格式

标签 r reshape

我正在努力将面板数据集从宽格式转换为长格式。数据集如下所示:

ID | KP1_430a | KP1_430b | KP1_430c | KP2_430a | KP2_430b | KP2_430c | KP1_1500a | ...  
1     ....
2     ....

KP1; KP2 到 KP7 描述了 Waves。
a,b 到 f 描述一个特定的项目。 (例如甲方从左到右的位置)

我想要长格式的数据。像这样:
ID | Party | Wave | 430 | 1500  
 1     1       1     ..    ..
 1     2       1     ..    ..
 .     .       .          
 1     1       2     ..    ..
 .     .       .         
 2     1       1     ..    ..  

我尝试使用 reshape 功能。但随着时间的推移,我在重新塑造它时遇到了问题,同时又在派对上出现了问题。

这是一个小的 data.frame 示例。
data <- data.frame(matrix(rnorm(10),2,10))  
data[,1] <- 1:2  
names(data) <- c("ID","KP1_430a" , "KP1_430b" , "KP1_430c" , "KP2_430a" , "KP2_430b ", "KP2_430c ", "KP1_1500a" ,"KP1_1500b", "KP1_1500c")

这就是我走了多远。
  data_long <- reshape(data,varying=list(names(data)[2:4],names(data)[5:7], names(data[8:10]),  
                            v.names=c("KP1_430","KP2_430","KP1_1500"),  
                           direction="long", timevar="Party")

问题仍然存在:我如何才能获得长格式的时变变量?有没有更优雅的方式来 reshape 这些数据?在上面的代码中,我必须为每个波和变量输入名称 (names(data)[2:4])。有了这个小的 data.frame 就可以了,但是数据集要大得多。

编辑:如何手动完成这种转换:我实际上已经这样做了,这给我留下了一页长的代码文件。
首先,将 KP1_430a 和 KP1_1500a 与 ID、Time=1 和 Party=1 列绑定(bind)。其次为所有各方 [b-f] 创建相同的对象,分别更改各方索引,并将其逐行附加。对其余的波 [2-7] 执行第 1 步和第 2 步,分别更改派对和时间变量,并将它们逐行附加。

最佳答案

通常分两步进行比较容易:首先使用 melt将您的数据放入“高”格式(除非已经是这种情况),然后使用 dcast将 ti 转换为更宽的格式。

library(reshape2)
library(stringr)

# Tall format
d <- melt(data, id.vars="ID")

# Process the column containing wave and party
d1 <- str_match_all( 
  as.character( d$variable ), 
  "KP([0-9])_([0-9]+)([a-z])" 
)
d1 <- do.call( rbind, d1 )
d1 <- d1[,-1]
colnames(d1) <- c("wave", "number", "party")
d1 <- as.data.frame( d1)
d <- cbind( d, d1 )

# Convert to the desired format
d <- dcast( d, ID + wave + party ~ number )

关于将面板数据宽格式 reshape 为长格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9004399/

相关文章:

python - 如何在 pandas & R 中没有任何聚合的情况下转置数据帧?

r - 多列条件合并

r - 在 ggplot2 中绘制线条和群体审美

r - Azure函数: How to trigger PS script on file addition to blob container to invoke R script processing

r - 是否有包或技术可用于计算 R 中的大阶乘?

python - 如何将一个添加到矩阵?

python - reshape numpy为滞后值添加额外维度

保留标签的同时删除ggplot图例符号

r - 在 R 中保存引用类的实例

重新排列数据以与数据对齐