Home > Net >  Convert list of vectors of unequal size into a data frame in R
Convert list of vectors of unequal size into a data frame in R

Time:01-06

I have a list of unequal elements below, where c includes everything in b and a; b includes everything in a and most of c.

myList <- list(a = c(1, 2, 3), b = c(1,2,4,3), c = c(1,2,3,4,5))

I want to create a data frame as shown below matching the elements in c. How do I do this?

a b c
1 1 1
2 2 2
3 3 3
NA 4 4
NA NA 5

CodePudding user response:

Convert each component to ts, use cbind.ts and convert to data frame.

as.data.frame(do.call("cbind", lapply(myList, ts)))

giving:

   a  b c
1  1  1 1
2  2  2 5
3  3  4 3
4 NA  3 4
5 NA NA 3

CodePudding user response:

   sapply(myList, function(x, y) `length<-`(y[y%in%x], length(y)), y = myList[['c']])
      a  b c
[1,]  1  1 1
[2,]  2  2 2
[3,]  3  3 3
[4,] NA  4 4
[5,] NA NA 5

CodePudding user response:

An alternative would be:

 do.call(cbind,
        lapply(1:length(myList),
               function(i) c(myList[[i]], rep(NA, (max(lengths(myList)) - lengths(myList)[i]))))
        )
  •  Tags:  
  • Related