我有许多列表列表,在每个列表中我需要提取的变量以稍微不同的方式嵌套。有没有一种简单的方法来搜索变量并将其提取出来?
示例列表
list1 <- list(AccountingSupplierParty = list(Party = list(PartyName = "Company Incorporated", PartyType = "The worst party")), DataSet = "Data Set 1")
list2 <- list(SupplierParty = list(Party = list(PartyName = "Company A/S", PartyType = "The best party")), DataSet = "Data Set 2")
我想提取&#34; PartyName&#34;。在巨大的数据集中学习变量的所有组合并不是那么有效,如下图所示:
Company1 <- list1$AccountingSupplierParty$Party$PartyName
Company2 <- list2$SupplierParty$Party$PartyName
我想要的输出是:
"Company Incorporated"
"Company A/S"
答案 0 :(得分:2)
您可以取消列出每个列表,然后清除所有未在PartyName
中结束的列表。
list1 <- list(AccountingSupplierParty = list(Party = list(PartyName = "Company Incorporated", PartyType = "The worst party")), DataSet = "Data Set 1")
list2 <- list(SupplierParty = list(Party = list(PartyName = "Company A/S", PartyType = "The best party")), DataSet = "Data Set 2")
c1 <- unlist(list1)
c1 <- c1[grepl("PartyName$", names(c1))]
AccountingSupplierParty.Party.PartyName
"Company Incorporated"
c2 <- unlist(list2)
c2 <- c2[grepl("PartyName$", names(c2))]
c2
SupplierParty.Party.PartyName
"Company A/S"
答案 1 :(得分:0)
您可以尝试使用rlist库。
https://cran.r-project.org/web/packages/rlist/rlist.pdf
library(rlist)
list.flatten(list1)[1]
list.flatten(list2)[1]
$AccountingSupplierParty.Party.PartyName
[1] "Company Incorporated"
$SupplierParty.Party.PartyName
[1] "Company A/S"
答案 2 :(得分:0)
你可以试试这个
dfs <- data.frame(lapply(list1, data.frame, stringsAsFactors = FALSE))
df1[ , grepl( "PartyName" , names( df1 ) ) ]
注意我使用了data.frame两次才能使stringAsFactors工作。 这会给你
[1] "Company Incorporated"
希望有所帮助,翁贝托