【问题标题】:How to flatten a deeply and irregularly nested list/dataframe/JSON in R如何在 R 中展平深度且不规则嵌套的列表/数据框/JSON
【发布时间】:2018-08-07 18:09:54
【问题描述】:

我想将 json 文件转换为数据框(数据框内没有任何嵌套列表)

temp <- jsonlite::fromJSON(txt ="https://unstats.un.org/SDGAPI/v1/sdg/GeoArea/Tree")

【问题讨论】:

    标签: r purrr jsonlite


    【解决方案1】:

    递归取消嵌套:

    library(tidyr)
    library(purrr)
    library(dplyr)
    
    recursive_unnest <- function(.data) {
      # Exit condition: no more 'children' list-column
      if (!"children" %in% names(.data) || !is.list(.data[["children"]])) return(.data)
      x <- unnest(.data)
      # Minor clean-up to make unnest work: replace NULLs with empty data frames
      x <- mutate_if(x, is.list, 
                     ~ map_if(.x, ~ is.null(.x) || identical(.x, list()), ~ data.frame(geoAreaCode = NA)))
      Recall(x)
    }
    recursive_unnest(temp)
    
    # Observations: 489
    # Variables: 16
    # $ geoAreaCode  <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,...
    # $ geoAreaName  <chr> "World", "World", "World", "World", "World", "World", "World", "Worl...
    # $ type         <chr> "Region", "Region", "Region", "Region", "Region", "Region", "Region"...
    # $ geoAreaCode1 <int> 10, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2...
    # $ geoAreaName1 <chr> "Antarctica", "Africa", "Africa", "Africa", "Africa", "Africa", "Afr...
    # $ type1        <chr> "Country", "Region", "Region", "Region", "Region", "Region", "Region...
    # $ geoAreaCode2 <int> NA, 15, 15, 15, 15, 15, 15, 15, 202, 202, 202, 202, 202, 202, 202, 2...
    # $ geoAreaName2 <chr> NA, "Northern Africa", "Northern Africa", "Northern Africa", "Northe...
    # $ type2        <chr> NA, "Region", "Region", "Region", "Region", "Region", "Region", "Reg...
    # $ geoAreaCode3 <int> NA, 12, 818, 434, 504, 729, 788, 732, 14, 14, 14, 14, 14, 14, 14, 14...
    # $ geoAreaName3 <chr> NA, "Algeria", "Egypt", "Libya", "Morocco", "Sudan", "Tunisia", "Wes...
    # $ type3        <chr> NA, "Country", "Country", "Country", "Country", "Country", "Country"...
    # $ geoAreaCode4 <int> NA, NA, NA, NA, NA, NA, NA, NA, 86, 108, 174, 262, 232, 231, 260, 40...
    # $ geoAreaName4 <chr> NA, NA, NA, NA, NA, NA, NA, NA, "British Indian Ocean Territory", "B...
    # $ type4        <chr> NA, NA, NA, NA, NA, NA, NA, NA, "Country", "Country", "Country", "Co...
    # $ children     <lgl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, ...
    

    【讨论】:

    • 非常感谢您的帮助,尤其是召回功能是我第一次听说。请问你为什么用.data代替data,用.x代替x。使用 dot with argument 背后的秘密是什么?谢谢
    • .data:没有秘密,它只是一个任意的有效变量名。 .x 略有不同:在 tidyverse 中,通常在 map 系列函数中,您可以将函数作为参数传递,并且匿名函数有一个简写语法,基本上 ~ .x + 1function(.x) .x + 1 的替代品,您可以在help("map") 中阅读更多内容,例如
    猜你喜欢
    • 2017-04-19
    • 2021-12-03
    • 2016-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多