0

I have a list that looks like this

[[1]]
[1] 1

[[2]]
[1] 2 3 4

[[3]]
[1] 5 6

I would like to turn it into a data frame like this

   A B C
1  1 
2  2 3 4 
3  5 6

Sadly, I do not know how to do this.

Could anyone give me the answer, please? Thank you

JMCrocs
  • 57
  • 6
  • I think [it](https://stackoverflow.com/questions/4227223/convert-a-list-to-a-data-frame) might be helpful – Adamm Oct 07 '20 at 12:42

2 Answers2

2

You can try the code below

data.frame(t(sapply(lst,`length<-`,max(lengths(lst)))))

or

data.frame(do.call(rbind,lapply(lst,`length<-`,max(lengths(lst)))))

giving

  X1 X2 X3
1  1 NA NA
2  2  3  4
3  5  6 NA

Data

lst <- list(1, 2:4, 5:6)

Update

It seems you have NULL in lst. In this case, you can try the code below

data.frame(do.call(rbind,lapply(replace(lst,!lengths(lst),NA),`length<-`,max(lengths(lst)))))

or

data.frame(t(sapply(replace(lst,!lengths(lst),NA),`length<-`,max(lengths(lst)))))

Example Given lst as

lst <- list(1,2:4,5:6,NULL,1:4)

> lst
[[1]]
[1] 1

[[2]]
[1] 2 3 4

[[3]]
[1] 5 6

[[4]]
NULL

[[5]]
[1] 1 2 3 4

we will get

> data.frame(do.call(rbind,lapply(replace(lst,!lengths(lst),NA),`length<-`,max(lengths(lst))))) 
  X1 X2 X3 X4
1  1 NA NA NA
2  2  3  4 NA
3  5  6 NA NA
4 NA NA NA NA
5  1  2  3  4

> data.frame(t(sapply(replace(lst,!lengths(lst),NA),`length<-`,max(lengths(lst)))))
  X1 X2 X3 X4
1  1 NA NA NA
2  2  3  4 NA
3  5  6 NA NA
4 NA NA NA NA
5  1  2  3  4
ThomasIsCoding
  • 80,151
  • 7
  • 17
  • 65
1

You could also use dplyr bind_rows() with this trick (I have used the data from @ThomasIsCoding many thanks):

library(dplyr)
#Code
df <- bind_rows(lapply(lst,function(x)as.data.frame(t(x))))

Output:

  V1 V2 V3
1  1 NA NA
2  2  3  4
3  5  6 NA
Duck
  • 38,442
  • 13
  • 38
  • 79