R将嵌套列表的元素写入csv

问题描述 投票:0回答:1

我有一个列表列表,由于某些JSON文件的结构,其中又有多个列表。每个列表具有相同的编号(即48个列表,其中1个列表,1个列表,1个列表,2个列表[在这里,我需要后两个中的第一个)。现在,问题是,我需要从所有这些列表中检索深度嵌套的数据。

作为可复制的示例。

列表结构大致如下(也许是另一层):

list1 = list(speech1 = 1, speech2 = 2)
list2 = list(list1, randomvariable="rando")
list3 = list(list2) #container
list4 = list(list3, name="name", stage="stage")
list5 = list(list4) #container
list6 = list(list5, date="date")
listmain1 = list(list6)
listmain2 = list(list6)
listmain3 = list(listmain1, listmain2)

结构应该像这样:

[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
[[1]][[1]][[1]][[1]]
[[1]][[1]][[1]][[1]][[1]]
[[1]][[1]][[1]][[1]][[1]][[1]]
[[1]][[1]][[1]][[1]][[1]][[1]][[1]]
[[1]][[1]][[1]][[1]][[1]][[1]][[1]]$speech1
[1] 1

[[1]][[1]][[1]][[1]][[1]][[1]][[1]]$speech2
[1] 2


[[1]][[1]][[1]][[1]][[1]][[1]]$randomvariable
[1] "rando"



[[1]][[1]][[1]][[1]]$name
[1] "name"

[[1]][[1]][[1]][[1]]$stage
[1] "stage"



[[1]][[1]]$date
[1] "date"



[[2]]
[[2]][[1]]
[[2]][[1]][[1]]
[[2]][[1]][[1]][[1]]
[[2]][[1]][[1]][[1]][[1]]
[[2]][[1]][[1]][[1]][[1]][[1]]
[[2]][[1]][[1]][[1]][[1]][[1]][[1]]
[[2]][[1]][[1]][[1]][[1]][[1]][[1]]$speech1
[1] 1

[[2]][[1]][[1]][[1]][[1]][[1]][[1]]$speech2
[1] 2


[[2]][[1]][[1]][[1]][[1]][[1]]$randomvariable
[1] "rando"



[[2]][[1]][[1]][[1]]$name
[1] "name"

[[2]][[1]][[1]][[1]]$stage
[1] "stage"



[[2]][[1]]$date
[1] "date"

最终结果将如下所示:

    date  name  speech1  speech2   
1    

2

我想从需要的变量中创建列,并从提取它们的列表中创建行。在上面的示例中,我需要从所有主列表中检索变量Speech1,Speech2,名称和日期,并将其转换为更简单的数据框。我不太确定执行此操作的最快方法,并且最近几天一直用lapply()和purrr来敲打我的头。理想情况下,我想将列表视为在列中具有扁平变量的rowID,但是这也很棘手。任何帮助表示赞赏。

r list nested-lists
1个回答
0
投票

通过遍历每个列表,将其展平并获取值,可以使用基数R快速实现它:

# Your data
list1 = list(speech1 = 1, speech2 = 2)
list2 = list(list1, randomvariable="rando")
list3 = list(list2) #container
list4 = list(list3, name="name", stage="stage")
list5 = list(list4) #container
list6 = list(list5, date="date")
listmain1 = list(list6)
listmain2 = list(list6)
listmain3 = list(listmain1, listmain2)

# Loop over each list inside listmain3
flatten_list <- lapply(listmain3, function(x) {
  # Flatten the list and extract the values that 
  # you're interested in
  unlist(x)[c("date", "name", "speech1", "speech2")]
})

# bind each separate listo into a data frame
as.data.frame(do.call(rbind, flatten_list))
#>   date name speech1 speech2
#> 1 date name       1       2
#> 2 date name       1       2

除非您希望将行名映射到特定于每个列表的某些值,否则行名应与列表数具有相同的顺序。也就是说,如果在48个嵌套列表上运行此命令,则行名将降至1:48,因此无需使用row.names参数。

© www.soinside.com 2019 - 2024. All rights reserved.