user15051990
user15051990

Reputation: 1895

Convert list of list object to dataframe in R

I have a list of list as given below. ANd I want to convert it into dataframe in the desired format.

myList:

[[1]]
NULL

[[2]]
[[2]]$`file`
[1] "ABC"

[[2]]$New
[1] 21

[[2]]$Old
[1] 42


[[3]]
[[3]]$`file`
[1] "CDF"

[[3]]$NEW
[1] 206

[[3]]$Old
[1] 84

And I want to convert this list of list object to dataframe in the desired format:

file   New   Old
ABC    21     42
CDF    206    84

Thanks in advance!

Upvotes: 12

Views: 42518

Answers (3)

989
989

Reputation: 12935

Something like (ls is your list):

df <- data.frame(matrix(unlist(ls), ncol = max(lengths(ls)), byrow = TRUE))

If column names matter, then

names(df) <- names(ls[[which(lengths(ls)>0)[1]]])

Upvotes: 9

akrun
akrun

Reputation: 887891

We can use map_df after converting to a tibble

library(tidyverse)
myList %>% 
   map_df(as_tibble)
# A tibble: 2 x 3
#  file    New   Old
#  <chr> <dbl> <dbl>
#1 ABC      21    42
#2 CDF     206    84

Or with bind_rows

bind_rows(myList)
# A tibble: 2 x 3
#  file    New   Old
#  <chr> <dbl> <dbl>
#1 ABC      21    42
#2 CDF     206    84

data

myList <- list(NULL, list(file = 'ABC', New = 21, Old = 42), 
                      list(file = 'CDF', New = 206, Old = 84))

Upvotes: 21

Rich Scriven
Rich Scriven

Reputation: 99371

It looks like the following would work.

do.call(rbind, lapply(list, as.data.frame))

where list is your list.

Upvotes: 8

Related Questions