Mevve
Mevve

Reputation: 159

Map function to sort JSON into data frame (with nested lists)

I'm using data from the Nobel prize API

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

with the following structure

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"
...

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.

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, ])

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"]]) ))

Upvotes: 1

Views: 142

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389175

Using purrr, you could do :

library(purrr)

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

Or in base R :

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

Upvotes: 2

Related Questions