'Nested list to dataframe [using purrr + map]
I've looked at a lot of posts so I'm sorry if this is redundant, but was hoping to get some help flattening a nested list:
test <- list()
test <- c(
list("A" = c(list("1"), list("2"), list("3"))),
list("B" = c(list("4"), list("5"), list("6")))
)
Desired Output
name subcat
1 A 1
2 A 2
3 A 3
4 B 4
5 B 5
6 B 6
I'm struggling to write a nested for loop but I'd really like to use purrr or something more elegant to create a dataframe with two columns: the subcat column, and a repeated column for the name for each element in the list.
Any help appreciated, even just pointing me to similar posts - thanks!
Solution 1:[1]
For these updated data you can try:
library(tidyverse)
enframe(test) %>% unnest_longer(value)
# A tibble: 6 x 2
# name value
# <chr> <chr>
#1 A 1
#2 A 2
#3 A 3
#4 B 4
#5 B 5
#6 B 6
Solution 2:[2]
We can do this in base R
with stack
stack(test)[2:1]
# ind values
#1 A 1
#2 A 2
#3 A 3
#4 B 4
#5 B 5
#6 B 6
Or using unlist/data.frame
data.frame(name = rep(names(test), lengths(test)), val = unlist(test))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | dhd |
Solution 2 | akrun |