【发布时间】:2022-01-04 18:40:35
【问题描述】:
由于time 变量(面板数据不平衡),我想组合不同长度的长格式数据帧:
set.seed(63)
#function to create a data frame that includes id, time and x
func1 <- function (size=5) {
x=sample(c(0,1), 1)
data.frame(time=1:size, x=x)}
#function to row combine data frames
func2 <- do.call("rbind", Map(function(x,y) {
data.frame(id=x, func1(y))
}, 1:5, 5))
#Sample 10 observations to create imbalanced panel data
dd <- func2[sample(nrow(func2), 10), ]
fd <- dd[with(dd, order(id, time)),]
> fd
id time x
1 1 1 0
2 1 2 0
3 1 3 0
4 1 4 0
5 1 5 0
10 2 5 1
13 3 3 0
17 4 2 0
18 4 3 0
21 5 1 0
最后,我想将其转换为宽格式,并根据 time 变量用 NA 填充 x 的跳过单元格。像这样的:
id x.time1 x.time2 x.time3 x.time4 x.time5
1 0 0 0 0 0
2 NA NA NA NA 1
3 NA NA 0 NA NA
4 NA 0 0 NA NA
5 0 NA NA NA NA
【问题讨论】:
-
是的,这是一个错字。我更正了。
标签: r time-series data-manipulation data-cleaning panel-data