I have code that a user kindly helped me with in this thread. It does exactly what I want it to, except the results are not stored in a dataframe.
## Setting up API Call
base_string1 <- "https.api.companyname/jurisdiction="
base_string2 <- "&date="
end_string <- "api_token=XYZ"
## Specifying objects to loop over
dates <- seq(as.Date("1990-01-01"), as.Date("2022-01-01"), by = "year")
dates <- paste(head(dates, -1), tail(dates-1, - 1), sep = ":")
countries<- paste0("eu_", c("fra", "ger"))
## Looping over
map_dfr(dates, function(dates){
map_dfr(states, function(countries){
api_string <- paste0(base_string1, countries, base_string2, dates, end_string)
print(api_string)
json <- jsonlite::fromJSON(api_string)
data.frame("countries" = countries,
"dates" = dates,
"total_number" = json[["results"]]$total_number)
})
})
This gives me
countries dates total_number
1 eu_ger 1990-01-01:1990-12-31 2404
2 eu_fra 1990-01-01:1990-12-31 2056
3 eu_ger 1991-01-01:1991-12-31 3490
4 eu_fra 1991-01-01:1991-12-31 6070
5 eu_ger 1992-01-01:1992-12-31 7808
6 eu_fra 1992-01-01:1992-12-31 1904
Which is the information I want, but I'd like to store it in a dataframe that I can access. I'd also like to call the countries "Germany" and France," and rather than the date range, I'd like to call it something like 1992 (and there's also a version where I go by month, in which case I'd like the value to be the year-month).
I've tried adding the below after the API call, but without success.
json_df<- as_tibble(json)
json_df <- data.frame("countries" = countries,
"dates" = dates,
"total_number" = json[["results"]]$total_number)
How do I store the results in a dataframe, and ideally also change the country names/dates?
CodePudding user response:
as suggested in the comments above try:
my_results <- map_dfr(dates, function(dates){
map_dfr(states, function(countries){
api_string <- paste0(base_string1, countries, base_string2, dates, end_string)
print(api_string)
json <- jsonlite::fromJSON(api_string)
data.frame("countries" = countries,
"dates" = dates,
"total_number" = json[["results"]]$total_number)
})
})