简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM