2017-04-24 22 views
0

我有許多列表的列表,並且在每個列表中,我需要提取的變量以稍微不同的方式嵌套。有沒有簡單的方法來搜索變量並提取它?R:從列表中搜索並提取變量

實施例列出

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") 

我想提取物 「PartyName」。

Company1 <- list1$AccountingSupplierParty$Party$PartyName 
Company2 <- list2$SupplierParty$Party$PartyName 

我想輸出是:

"Company Incorporated" 
"Company A/S" 
+0

你應該讓你的榜樣[重複性(http://stackoverflow.com/questions/5963269/how-to-make-a-great通過添加'dput(list1)'和'dput(list2)'的結果,來重新生成實例#5963610)。 – alistaire

+0

謝謝,我現在將舉例 –

+0

您可以只是抽象出更改的部分:'sapply(list(list1,list2),function(x){x [[1]] $ Party $ PartyName})' – alistaire

回答

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" 
+0

謝謝,這是訣竅。 –

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" 
0

你可以試試這個

dfs <- data.frame(lapply(list1, data.frame, stringsAsFactors = FALSE)) 
df1[ , grepl("PartyName" , names(df1)) ] 

通知我用data.frame兩次,才能使stringAsFactors工作。 這會給你

[1] "Company Incorporated" 

希望幫助,翁