Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...