问题
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!
回答1:
You can try :
library(purrr)
test1 <- flatten(test)
do.call(rbind.data.frame, map2(map_chr(test1, `[[`, 'name'),
map(test1, `[[`, 'subcat'), cbind))
# V1 V2
#1 A 1
#2 A 2
#3 A 3
#4 B 4
#5 B 5
#6 B 6
For the updated data :
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
回答2:
library(dplyr)
library(purrr)
library(tidyr)
test %>%
as_tibble() %>% # dplyr
mutate(category = map(category, as_tibble)) %>% # purrr
unnest(cols = "category") %>% # tidyr
unnest(cols = "subcat")
# A tibble: 6 x 2
name subcat
<chr> <chr>
1 A 1
2 A 2
3 A 3
4 B 4
5 B 5
6 B 6
This approach converts your list into a dataframe, then each list-element of it into a dataframe, then unnests them successively.
回答3:
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))
来源:https://stackoverflow.com/questions/59905687/nested-list-to-dataframe-using-purrr-map