嵌套列表到数据框[使用purrr +映射] [英] Nested list to dataframe [using purrr + map]
本文介绍了嵌套列表到数据框[使用purrr +映射]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看了很多文章,所以很抱歉,这很多余,但是希望能得到一些使拼合嵌套列表扁平化的帮助:
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
我正在努力编写一个嵌套的for循环,但是我真的很想使用purrr或更优雅的方法来创建一个具有两列的数据框:subcat列,以及一个重复的列,用于表示元素中每个元素的名称.列表.
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!
推荐答案
您可以尝试:
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
这篇关于嵌套列表到数据框[使用purrr +映射]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文