【问题标题】:R: Search and extract variables from lists of listsR:从列表列表中搜索和提取变量
【发布时间】:2017-04-24 07:06:31
【问题描述】:

我有许多列表,在每个列表中,我需要提取的变量都以稍微不同的方式嵌套。有没有一种简单的方法来搜索变量并提取它?

示例列表

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"

【问题讨论】:

  • 您应该通过添加dput(list1)dput(list2) 的结果来创建您的示例reproducible
  • 谢谢,我现在就做例子
  • 你可以抽象出变化的部分:sapply(list(list1, list2), function(x){x[[1]]$Party$PartyName})

标签: r list search extract nested-lists


【解决方案1】:

您可以取消列出每个列表,然后清除所有不以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" 

【讨论】:

    【解决方案2】:

    你可以试试 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"
    

    【讨论】:

      【解决方案3】:

      你可以试试这个

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

      请注意,我使用 data.frame 两次才能使 stringAsFactors 工作。 这会给你

      [1] "Company Incorporated"
      

      希望对您有所帮助,翁贝托

      【讨论】:

        猜你喜欢
        • 2021-11-14
        • 2021-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-20
        相关资源
        最近更新 更多