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
  • 77
  • 7
  • 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
  • 96,636
  • 9
  • 24
  • 81
  • Thomas, so the `length<-` part makes the length of each vector in list 'lst' as 3, which is the max length of all vectors in that list? – Karthik S Oct 07 '20 at 13:04
  • 1
    @KarthikS Yes, you got it! – ThomasIsCoding Oct 07 '20 at 13:06
  • With the second option, it works but I have this error `1: In lapply(meps, `length<-`, max(lengths(meps))) : length of NULL cannot be changed 2: In lapply(meps, `length<-`, max(lengths(meps))) : length of NULL cannot be changed` – JMCrocs Oct 07 '20 at 13:48
  • @JMCrocs It seems you have `NULL` in your list. Please see my update for that. – ThomasIsCoding Oct 07 '20 at 18:59
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
  • 39,058
  • 13
  • 42
  • 84