Sati Sati - 1 month ago 8
R Question

R - Coerce list into dataframe, keeping column-variables together

I have a list of named vectors:

> x <- list(c(a=1, b=2, c=3, d=4),c(a=5, b=6 ,c=7 ,d=8),c(a=32, c=46, d=55, e=100))
> x
[[1]]
a b c d
1 2 3 4

[[2]]
a b c d
5 6 7 8

[[3]]
a c d e
32 46 55 100


I would like to coerce this into a data.frame such that values named similarly fall into one column:

> y <- data.frame(a=c(1,5,32), b=c(2,6,NA), c=c(3,7,46), d=c(4,8,55), e=c(NA,NA,100))
> y
a b c d e
1 1 2 3 4 NA
2 5 6 7 8 NA
3 32 NA 46 55 100


Is there an easy way to do this?

Answer Source

Try this with the dplyr package:

require(dplyr)

data.frame(bind_rows(!!! x))

Output:

   a  b  c  d   e
1  1  2  3  4  NA
2  5  6  7  8  NA
3 32 NA 46 55 100