-1

I have a large list of lists full of IDs with the following properties

list1 <- c(145540,145560, 157247, 145566)
list2 <- c(166927, NA, NA, NA)
list3 <- c(145592, 145560, 145566, NA)
list <- list(list1, list2, list3)

Now I would like to coerce this large list to a data.frame while keeping the list properties of the nested lists. The desired output should look like this:

list1 list2 list3
145540 166927 145592
145560 NA 145560
157247 NA 145566
145566 NA NA

Thank you very much for your help.

`

  • Please explain how you encountered the problem you're trying to solve, and any difficulties that have prevented you from solving it yourself. – cptwonton Feb 05 '18 at 18:03
  • You don't have any nested lists there. You are working with three atomic vectors. Let's have a `dput()` of the desired result. Not sure what the final result is supposed to be, but `as.data.frame(list)` should be fine (but with ugly names). – Rich Scriven Feb 05 '18 at 18:13

2 Answers2

0

Just rowbind together your lists of vectors (assuming you have just vectors as elements of your upper level list)

as.data.frame(sapply(list, rbind))
     V1   V2   V3
1 145540 166927 145592
2 145560     NA 145560
3 157247     NA 145566
4 145566     NA     NA
Felipe Alvarenga
  • 2,572
  • 1
  • 17
  • 36
0
do.call(cbind.data.frame,list)
  c(145540, 145560, 157247, 145566) c(166927, NA, NA, NA)
1                            145540                166927
2                            145560                    NA
3                            157247                    NA
4                            145566                    NA
  c(145592, 145560, 145566, NA)
1                        145592
2                        145560
3                        145566
4                            NA
> Reduce(cbind.data.frame,list)
    init x[[i]] x[[i]]
1 145540 166927 145592
2 145560     NA 145560
3 157247     NA 145566
4 145566     NA     NA
> Reduce(cbind,list)
       init              
[1,] 145540 166927 145592
[2,] 145560     NA 145560
[3,] 157247     NA 145566
[4,] 145566     NA     NA

Then you can set the names.

Although on the other hand if the names were preset ie list <- list(list1=list1, list2=list2, list3=list3) then

do.call(cbind.data.frame,list)

   list1  list2  list3
1 145540 166927 145592
2 145560     NA 145560
3 157247     NA 145566
4 145566     NA     NA
Onyambu
  • 67,392
  • 3
  • 24
  • 53