12

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!

user15051990
  • 1,835
  • 2
  • 28
  • 42

3 Answers3

21

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))
akrun
  • 874,273
  • 37
  • 540
  • 662
8

It looks like the following would work.

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

where list is your list.

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
  • `Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : arguments imply differing number of rows: 1, 0` – PM0087 Apr 22 '20 at 15:45
8

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]]])
989
  • 12,579
  • 5
  • 31
  • 53
  • 1
    `Warning message: In matrix(unlist(myLIST), ncol = max(lengths(myLIST)), byrow = TRUE) : data length [20000] is not a sub-multiple or multiple of the number of rows [1000]` – PM0087 Apr 22 '20 at 15:47