假设我们有以下函数
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)
}
本质上,您可以在函数中输入一年,它会从第1个月返回该年的tibble(即'/1'
位(。
如何循环该函数,使其首先返回tibble,例如从2019年到第1个月(用/1.json
表示(,然后从第2个月(由/2.json
表示(等,直到第12个月返回tibble?
从本质上讲,链接的数字部分需要增加1,直到12,以便函数返回一个包含所有12个月数据的数据帧。
您有一个sprintf()
语句,它实际上并没有做任何事情,但可以很容易地扩展到处理月份和年份。(这些琐碎的东西在这里似乎并没有起到多大作用,所以我转换回基本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)
有了tidyverse,你可以做purrr::map(1:12, ~test_function(2021, .))