I want to combine data frames in long format with different length because of the time
variable (imbalanced panel data):
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
In the end, I want to convert it to wide format and and fill with NA the skipped cells of x
based on the time
variable . Something like this:
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