user14892366
user14892366

Reputation:

How to write simple loop in R which updates number in URL?

Suppose we have the following function

library("jsonlite")
library("dplyr")

test_function <- function(year) {

link <- sprintf(paste0('https://api.hello/', year, '/1.json'))
  
  data_frame <- fromJSON(link) %>%
    pluck(2) %>%
    as_tibble

return(data_frame)

}

Essentially you can enter a year into the function and it returns a tibble for that year from month 1 (i.e. the '/1' bit).

How can the function be looped so that it first returns a tibble e.g. from year 2019, month 1 (represented by /1.json), then returns a tibble from month 2 (represented by /2.json), etc., up to month 12?

Essentially the number part of the link needs to increase by 1 until 12, so that the function returns a data frame with data from all 12 months.

Upvotes: 0

Views: 30

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226182

You had a sprintf() statement that wasn't really doing anything but which could be easily extended to handle both month and year. (The tidyverse stuff didn't really seem to be doing much here, so I converted back to base R ...)

test_function <- function(year, month) {
    link <- sprintf('https://api.hello/%d/%d.json', year, month)
    as_tibble(fromJSON(link)[[2]])
}
res <- list()
for (i in 1:12) res[[i]] <- test_function(2021, i)

With tidyverse, you could do purrr::map(1:12, ~test_function(2021, .))

Upvotes: 1

Related Questions