Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert nested list with different datatypes to dataframe?

Tags:

r

tidyr

tidyverse

I have a list with nested elements of different types

library(tidyverse)

# list to be transfomed into a dataframe/tibble
mylist <- 
  list(
    lois = list(
      hair = list(color = "orange", form = "flat"),
      sex = "female"
    )
  )

# structure
str(mylist)
#> List of 1
#>  $ lois:List of 2
#>   ..$ hair:List of 2
#>   .. ..$ color: chr "orange"
#>   .. ..$ form : chr "flat"
#>   ..$ sex : chr "female"

The goal is to convert this list into a dataframe/tibble. The desired output is

# A tibble: 3 x 4
  name  value_id attribute text  
  <chr> <chr>    <chr>     <chr> 
1 lois  hair     color     orange
2 lois  hair     form      flat  
3 lois  sex      NA        female

I tried tidyr::unnest_longer(). But is struggles to unnest because there are different types in column value:

# unnest_longer does not work like this
mylist %>% 
  enframe() %>% 
  unnest_longer(col = value) %>% 
  unnest_longer(col = value)
#> Error: Can't combine `..1$value` <list> and `..2$value` <character>.

Created on 2021-01-13 by the reprex package (v0.3.0)

What is a good solution for this problem?

like image 948
piptoma Avatar asked Jun 07 '26 17:06

piptoma


1 Answers

One option is to use the rrapply library:

rrapply(mylist, how = "melt")

    L1   L2    L3  value
1 lois hair color orange
2 lois hair  form   flat
3 lois  sex  <NA> female
like image 150
tmfmnk Avatar answered Jun 10 '26 06:06

tmfmnk