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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With