Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list of list object to dataframe in R

Tags:

list

dataframe

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!

like image 244
user15051990 Avatar asked Jun 09 '18 19:06

user15051990


People also ask

How do I convert a list to a numeric Dataframe in R?

To convert R List to Numeric value, use the combination of the unlist() function and as. numeric() function. The unlist() function in R produces a vector that contains all the atomic components.


2 Answers

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))
like image 79
akrun Avatar answered Sep 17 '22 13:09

akrun


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]]])
like image 45
989 Avatar answered Sep 17 '22 13:09

989