我有一组嵌套列表的数据,每个顶层列表成员都有描述符(但不一定相同),然后是一个子列表,这些子列表可以有子列表,以此类推。子列表的深度是任意的。这是一个小的最简示例:
family <- list(
list(name = "Alice", age = 40, eyes = "blue", children = list(
list(name = "Bob", age = 20, eyes = "blue"),
list(name = "Charlie", age = 18, eyes = "brown")
)),
list(name = "Dan", age = 12, eyes = "green"),
list(name = "Erin", age = 69, eyes = "green", children = list(
list(name = "Frank", age = 45, eyes = "blue", children = list(
list(name = "George", age = 24, eyes = "blue", children = list(
list(name = "Harry", age = 2, eyes = "green")
)),
list(name = "Ingrid", age = 22, eyes = "brown", hair = "brown"),
list(name = "Jack", age = 29, eyes = "brown")
)),
list(name = "Karen", age = 43),
list(name = "Larry", age = 21, eyes = "blue")
))
)
> str(family, max.level = 2)
List of 3
$ :List of 4
..$ name : chr "Alice"
..$ age : num 40
..$ eyes : chr "blue"
..$ children:List of 2
$ :List of 3
..$ name: chr "Dan"
..$ age : num 12
..$ eyes: chr "green"
$ :List of 4
..$ name : chr "Erin"
..$ age : num 69
..$ eyes : chr "green"
..$ children:List of 3
理想情况下,我希望创建一个数据框,使每一行代表一个家庭成员,每一列代表列表中的一个属性:
name age eyes
1 Alice 40 blue
2 Bob 20 blue
3 Charlie 18 brown
(etc)
但是如何递归地进行到任意深度还不清楚。我已经使用
map(family, ~ .$name)
获取了顶层成员,但我不知道如何深入了解更多。由于部分成员没有子元素使得此过程变得复杂。我已经查看了purrr文档,但是找不到任何能够帮助的内容。也许我没有使用正确的术语。
欢迎提供建议。谢谢!