【问题标题】:R transform output of a loop function from embedded lists to dataframeR将循环函数的输出从嵌入式列表转换为数据框
【发布时间】:2021-01-26 00:15:31
【问题描述】:

我正在运行一个循环来从 API 中提取数据。具体来说,我有一个庞大的物种数据集,并且正在使用国际自然保护联盟的 API 来消除 10,000 多个物种面临的威胁。我用来提取此信息的循环是 -

result <- vector('list', length(df$scientific_name))

for (i in df$scientific_name) {
  result[[i]] <- rl_threats(name=i, key = '1234', parse = TRUE)
}

这成功地传递了 i 的物种名称(学名)并拉动了对该物种的威胁。但是问题是输出对我来说不是特别有用。输出是一个像这样有 3 层嵌套的列表 -

>Result
    >Species name
         >Results data frame _by_

这个输出很难分析,我想把它转换成数据框

下面的代码用于将列表中的单个物种转换为数据框,但我需要对数据集中的 10,000 多个物种中的每一个都执行此操作。我猜想写一个新循环或修改上面的循环是最好的方法,但不知道如何让它工作。

test1<-data.frame(result[26])

理想的输出应该是一个看起来像这样的数据框

         species name \ threat code \ threat title 
species1
species2
species3

感谢您的帮助!

编辑- 根据请求,这就是 dput 命令的输出样子

dput(head(result))

list(`Myxine glutinosa` = list(name = "Myxine glutinosa", result = structure(list(
    code = c("5.4", "5.4.2"), title = c("Fishing & harvesting aquatic resources", 
    "Intentional use: (large scale) [harvest]"), timing = c("Ongoing", 
    "Ongoing"), scope = c(NA, NA), severity = c(NA, NA), score = c("Low Impact: 3", 
    "Low Impact: 3"), invasive = c(NA, NA)), class = "data.frame", row.names = 1:2)), 
    `Myxine ios` = list(name = "Myxine ios", result = list()), 
    `Lampetra fluviatilis` = list(name = "Lampetra fluviatilis", 
        result = list()), `Lethenteron camtschaticum` = list(
        name = "Lethenteron camtschaticum", result = structure(list(
            code = c("5.4", "5.4.1", "7.2", "7.2.11"), title = c("Fishing & harvesting aquatic resources", 
            "Intentional use: (subsistence/small scale) [harvest]", 
            "Dams & water management/use", "Dams (size unknown)"
            ), timing = c("Ongoing", "Ongoing", "Ongoing", "Ongoing"
            ), scope = c("Unknown", "Unknown", "Unknown", "Unknown"
            ), severity = c("Unknown", "Unknown", "Unknown", 
            "Unknown"), score = c("Unknown", "Unknown", "Unknown", 
            "Unknown"), invasive = c(NA, NA, NA, NA)), class = "data.frame", row.names = c(NA, 
        4L))), `Petromyzon marinus` = list(name = "Petromyzon marinus", 
        result = list()), `Carcharhinus altimus` = list(name = "Carcharhinus altimus", 
        result = structure(list(code = c("5.4", "5.4.3", "5.4.4"
        ), title = c("Fishing & harvesting aquatic resources", 
        "Unintentional effects: (subsistence/small scale) [harvest]", 
        "Unintentional effects: (large scale) [harvest]"), timing = c("Ongoing", 
        "Ongoing", "Ongoing"), scope = c("Majority (50-90%)", 
        "Majority (50-90%)", "Majority (50-90%)"), severity = c("Slow, Significant Declines", 
        "Slow, Significant Declines", "Slow, Significant Declines"
        ), score = c("Medium Impact: 6", "Medium Impact: 6", 
        "Medium Impact: 6"), invasive = c(NA, NA, NA)), class = "data.frame", row.names = c(NA, 
        3L))))

【问题讨论】:

  • 嗨 Cyph,您能否发布一些输出以使其成为可重现的示例? dput(head(result)) 可能会工作

标签: r loops


【解决方案1】:

看起来lapply 循环运行良好!

result_list <- lapply(result, function(spec){
  if(length(spec$result)){
    data.frame(species_name=spec$name, threat_code=spec$result$code, threat_title=spec$result$title)
  }
})
result_df <- do.call(what = rbind, result_list)
rownames(result_df) <- NULL

【讨论】:

  • 这行得通,非常感谢!会让我永远弄清楚。
【解决方案2】:

你可以使用purrrmap_df

new <- purrr::map_df(result, `[[`, 'result', .id = 'species')
new
#                  species   code                                                      title
#1          Myxine glutinosa    5.4                     Fishing & harvesting aquatic resources
#2          Myxine glutinosa  5.4.2                   Intentional use: (large scale) [harvest]
#3 Lethenteron camtschaticum    5.4                     Fishing & harvesting aquatic resources
#4 Lethenteron camtschaticum  5.4.1       Intentional use: (subsistence/small scale) [harvest]
#5 Lethenteron camtschaticum    7.2                                Dams & water management/use
#6 Lethenteron camtschaticum 7.2.11                                        Dams (size unknown)
#7      Carcharhinus altimus    5.4                     Fishing & harvesting aquatic resources
#8      Carcharhinus altimus  5.4.3 Unintentional effects: (subsistence/small scale) [harvest]
#9      Carcharhinus altimus  5.4.4             Unintentional effects: (large scale) [harvest]

#   timing             scope                   severity            score invasive
#1 Ongoing              <NA>                       <NA>    Low Impact: 3       NA
#2 Ongoing              <NA>                       <NA>    Low Impact: 3       NA
#3 Ongoing           Unknown                    Unknown          Unknown       NA
#4 Ongoing           Unknown                    Unknown          Unknown       NA
#5 Ongoing           Unknown                    Unknown          Unknown       NA
#6 Ongoing           Unknown                    Unknown          Unknown       NA
#7 Ongoing Majority (50-90%) Slow, Significant Declines Medium Impact: 6       NA
#8 Ongoing Majority (50-90%) Slow, Significant Declines Medium Impact: 6       NA
#9 Ongoing Majority (50-90%) Slow, Significant Declines Medium Impact: 6       NA

然后您可以select 并仅保留您想要的来自new 的列。

【讨论】:

    猜你喜欢
    • 2021-08-21
    • 2020-04-13
    • 2020-11-02
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 2015-04-16
    相关资源
    最近更新 更多