Reputation: 1845
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")))
)
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!
Upvotes: 0
Views: 2217
Reputation: 388982
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
Upvotes: 5
Reputation: 887128
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))
Upvotes: 0