我的任务需要按周进行多次api调用。我想通过purrr
将所有这些数据与简明的代码一起追加,但我很难在我的函数中使Sys.sleep
工作。
以下是一些虚假数据。我假装这是API后端:
#call 1
week1 <- as_tibble(list(week = rep(1,7),value = rnorm(7,0,1)))
#call 2
week2 <- as_tibble(list(week = rep(2,7),value = rnorm(7,0,1)))
#call 3
week3 <- as_tibble(list(week = rep(3,7),value = rnorm(7,0,1)))
#append
pretend_full_api_data <- bind_rows(week1, week2, week3)
此功能有效
by_api_call <- function(weeknumber){
weeki <- pretend_full_api_data %>%
filter(week == weeknumber)
}
seq(from = 1, to = 3) %>%
map_df(~by_api_call(.))
问题是API通常需要休眠时间。所以我试着修改如下:
by_api_call <- function(weeknumber){
weeki <- pretend_full_api_data %>%
filter(week == weeknumber)
Sys.sleep(2) #required sleep for API calls
}
seq(from = 1, to = 3) %>%
map_df(~by_api_call(.))
上面的代码返回0 rows
。上述功能有什么问题?
答案 0 :(得分:0)
实际上这不起作用,因为函数by_api_call
没有返回任何内容。您需要添加函数return
以实际从函数中检索某些内容。
如果您需要查看技术讨论,请参阅Hadley Wickham撰写的Advanced R一书(R语言中最有价值的玩家)。
您的代码需要进行此调整,以实际执行所需的工作
# API stuff..
# this is the function that actually works...
by_api_call <- function(weeknumber){
weeki <- pretend_full_api_data %>%
filter(week == weeknumber)
Sys.sleep(2) #required sleep for API calls
return(weeki) # return is your friend...
}
# calling the API function
week_numbers <- seq(from = 1, to = 3, by = 1)
(map_df(week_numbers, by_api_call))