Sati
Sati

Reputation: 726

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?

Upvotes: 1

Views: 76

Answers (4)

www
www

Reputation: 4224

Try this with the dplyr package:

require(dplyr)

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

#or for a tibble, use: 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

Upvotes: 1

Andrew Gustar
Andrew Gustar

Reputation: 18425

You can do this easily with purrr::map_df and dplyr::bind_rows

library(purrr)
library(dplyr)
map_df(x,bind_rows)

# A tibble: 3 x 5
      a     b     c     d     e
  <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     2     3     4    NA
2     5     6     7     8    NA
3    32    NA    46    55   100

Upvotes: 2

Parfait
Parfait

Reputation: 107567

Consider base R:

df <- do.call(rbind, lapply(x, function(i) 
                            data.frame(a=i['a'], b=i['b'], c=i['c'], 
                                       d=i['d'], e=i['e'])))
row.names(df) <- NULL

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

Upvotes: 0

akrun
akrun

Reputation: 887008

We can use data.table

library(data.table)
rbindlist(lapply(x, as.data.frame.list), fill = TRUE)
#    a  b  c  d   e
#1:  1  2  3  4  NA
#2:  5  6  7  8  NA
#3: 32 NA 46 55 100

Or using base R

un1 <- unique(unlist(lapply(x, names)))
do.call(rbind, lapply(x, function(y) {
   y[setdiff(un1, names(y))] <- NA
   y[un1]}))

Upvotes: 2

Related Questions