【问题标题】:Extracting to a data frame from a JSON generated multi-level list with occasional missing elements从 JSON 生成的多级列表中提取到数据框,偶尔缺少元素
【发布时间】:2019-01-02 17:08:40
【问题描述】:

我正在通过 API 提取足球数据 - 结果 JSON 作为列表返回; dput 示例如下:

list(list(id = 10332894L, league_id = 8L, season_id = 12962L, 
aggregate_id = NULL, venue_id = 201L, localteam_id = 51L, 
visitorteam_id = 27L, weather_report = list(code = "drizzle", 
    temperature = list(temp = 53.92, unit = "fahrenheit"), 
    clouds = "90%", humidity = "87%", wind = list(speed = "12.75 m/s", 
        degree = 200L)), attendance = 25098L, leg = "1/1", 
deleted = FALSE, referee = list(data = list(id = 15267L, 
    common_name = "L. Probert", fullname = "Lee Probert", 
    firstname = "Lee", lastname = "Probert"))), list(id = 10332895L, 
league_id = 8L, season_id = 12962L, aggregate_id = NULL, 
venue_id = 340L, localteam_id = 251L, visitorteam_id = 78L, 
weather_report = list(code = "drizzle", temperature = list(
    temp = 50.07, unit = "fahrenheit"), clouds = "90%", humidity = "93%", 
    wind = list(speed = "6.93 m/s", degree = 160L)), attendance = 22973L, 
leg = "1/1", deleted = FALSE, referee = list(data = list(
    id = 15273L, common_name = "M. Oliver", fullname = "Michael Oliver", 
    firstname = "Michael", lastname = "Oliver"))))

我目前正在使用 for 循环进行提取 - 当完整数据中有数百个时,reprex 会显示 2 个顶级列表项。使用循环的主要缺点是有时会丢失导致循环停止的值。我想将其移至purrr,但我正在努力使用at_depthmodify_depth 提取第二级嵌套项。巢内还有巢,确实增加了复杂性。

最终状态应该是一个整洁的数据框 - 从这些数据中,df 将只有 2 行,但会有很多列,每列代表一个项目,无论该项目嵌套在此列表中的哪个位置。如果缺少某些东西,那么它应该是一个 NA 值。

一个解决方案的理想场景,即使它可能不优雅,每个级别/嵌套项目都有一个数据框,然后可以在以后绑定在一起。

谢谢。

【问题讨论】:

    标签: r purrr


    【解决方案1】:

    步骤1:使用社区wiki的功能hereNULL替换为NA

    simple_rapply <- function(x, fn)
    {
      if(is.list(x))
      {
        lapply(x, simple_rapply, fn)
      } else
      {
        fn(x)
      }
    }    
    non.null.l <- simple_rapply(l, function(x) if(is.null(x)) NA else x)
    

    第二步:

    library(purrr)
    map_df(map(non.null.l,unlist),bind_rows)
    

    【讨论】:

    • 谢谢 - 做得非常好,但是嵌套子列表中的一些项目没有被提取。因此,如果您查看子列表 my_list[[1]][["weather_report"]] ,则会为 weather 创建一个列,但该值来自 my_list[[1]][["weather_report"]][["code"]] 并且未解包进一步的子列表,也未将项目包含在与 @ 相同的级别987654329@。有任何想法吗?再次感谢。
    • @nycrefugee 很高兴为您提供帮助。我认为 foldel 的程序是为两级列表设计的,而不是为多级列表设计的,这是导致最终 df 问题的原因。请再次检查是否有任何问题。最后我们走这条路是因为aggregate_id 因为它的NULLunlist 会丢弃它,如果你不需要它,你可以直接做step2。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 2023-03-10
    相关资源
    最近更新 更多