Love-R
Love-R

Reputation: 818

LIst of lists in R into a data.frame - inconsistent variable names

I have a list of lists and I want to convert it into a dataframe. The challenge is that there are missing variables names in lists (not NA's but the variable is missing completely).

To illustrate on example: from

my_list <- list() 
my_list[[1]] <- list(a = 1, b = 2, c = 3)
my_list[[2]] <- list(a = 4, c = 6)

I would like to get

     a  b c
[1,] 1  2 3
[2,] 4 NA 6

Upvotes: 0

Views: 172

Answers (3)

akrun
akrun

Reputation: 887018

Another option is

library(reshape2)
as.data.frame(acast(melt(my_list), L1~L2, value.var='value'))
#  a  b c
#1 1  2 3
#2 4 NA 6

Or as @David Arenburg suggested a wrapper for melt/dcast would be recast

recast(my_list, L1 ~ L2, value.var = 'value')[, -1]
#  a  b c
#1 1  2 3
#2 4 NA 6

Upvotes: 2

erasmortg
erasmortg

Reputation: 3278

Another answer, this requires to change the class of the arguments to data.frames:

 library(plyr)
 lista <- list(a=1, b=2, c =3)
 listb <- list(a=4, c=6)
 lista <- as.data.frame(lista)
 listb <- as.data.frame(listb)
 my_list <- list(lista, listb)
 my_list <- do.call(rbind.fill, my_list)
 my_list
   a  b c
 1 1  2 3
 2 4 NA 6

Upvotes: 1

Tutuchan
Tutuchan

Reputation: 1567

You can use the bind_rows function from the dplyr package :

my_list <- list() 
my_list[[1]] <- list(a = 1, b = 2, c = 3)
my_list[[2]] <- list(a = 4, c = 6)
dplyr::bind_rows(lapply(my_list, as.data.frame))

This outputs:

Source: local data frame [2 x 3]
  a  b c
1 1  2 3
2 4 NA 6

Upvotes: 1

Related Questions