将 JSON 排序为数据框的映射函数(带有嵌套列表) [英] Map function to sort JSON into data frame (with nested lists)

查看:37
本文介绍了将 JSON 排序为数据框的映射函数(带有嵌套列表)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是来自 诺贝尔奖 API

library(httr)
url = "http://api.nobelprize.org/v1/prize.json"
resp = GET(url, query = list(category = "economics", year = 2000, yearTo = 2019))

具有以下结构

str(content(resp))
>List of 1
> $ prizes:List of 51
>  ..$ :List of 3
>  .. ..$ year     : chr "2019"
>  .. ..$ category : chr "economics"
>  .. ..$ laureates:List of 3
>  .. .. ..$ :List of 5
>  .. .. .. ..$ id        : chr "982"
>  .. .. .. ..$ firstname : chr "Abhijit"
>  .. .. .. ..$ surname   : chr "Banerjee"
>  .. .. .. ..$ motivation: chr "\"for their experimental approach to alleviating global poverty\""
>  .. .. .. ..$ share     : chr "3"
...

我想将 year 和 id 排序到同一个数据框中.请注意,每年可能会有一位或几位诺贝尔奖获得者.

I want to sort year and id into the same data frame. Note that for each year there can be one or several Nobel laureates.

我知道如何使用嵌套的 for 循环来做到这一点

I know how to do this with nested for loops

laureates <- data.frame(year = NA, id = NA)

for(i in 1:length(content(resp)$prizes)){
  year <- content(resp)$prizes[[i]][["year"]]
  for(k in 1:length(content(resp)$prizes[[i]]$laureates) ){
    id <- content(resp)$prizes[[i]]$laureates[[k]][["id"]]
    laureates[nrow(laureates)+1, c("year", "id")] <- c(year, id)
  }
}
 

head(laureates[-1, ])

但我不知道如何在tidyverse"中做到这一点使用 purrr 包中的地图功能进行时尚.最近"我来了是

But I can't figure out how to do this in a "tidyverse" fashion using map functionality from the purrr package. The "closest" I have came is

laureates <- map_df(content(resp)$prizes, ~data.frame(year = .x[["year"]], id = map(.x$laureates, ~.x[["id"]]) ))

推荐答案

使用 purrr,你可以:

library(purrr)

tmp <- content(resp)$prizes
result <- map_df(tmp, function(x) 
                    data.frame(year = x$year, 
                               id  = map_chr(x$laureates, `[[`, 'id')))

或在基数 R 中:

result <- do.call(rbind, lapply(tmp, function(x) 
                data.frame(year =  x$year, 
                           id = sapply(x$laureates, `[[`, 'id'))))

这篇关于将 JSON 排序为数据框的映射函数(带有嵌套列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆