0

I have a number of lists of lists, and in each of them the variable I need to extract is nested in a slightly different way. Is there a simple way to search for the variable and to extract it?

Example lists

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

I would like to extract "PartyName". It is not so efficient to learn all combinations of variables in a huge dataset as illustrated underneath:

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

The output I would like is:

"Company Incorporated"
"Company A/S"
Esben Eickhardt
  • 3,183
  • 2
  • 35
  • 56
  • You should make your example [reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example#5963610) by adding the results of `dput(list1)` and `dput(list2)`. – alistaire Apr 24 '17 at 07:14
  • Thanks, I will make the example now – Esben Eickhardt Apr 24 '17 at 07:17
  • You could just abstract out the part that changes: `sapply(list(list1, list2), function(x){x[[1]]$Party$PartyName})` – alistaire Apr 24 '17 at 08:33

3 Answers3

2

You could unlist each list and then weed out all that do not end in 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" 
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
0

You can try the rlist library.
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

You could try this

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

Notice I used data.frame twice to be able to make stringAsFactors work. This will give you

[1] "Company Incorporated"

Hope that helps, Umberto

Umberto
  • 1,387
  • 1
  • 13
  • 29