我正在尝试创建与给定日期从API收到的响应相对应的csv文件。
创建一个循环似乎很合乎逻辑,而不是每次我想要一个新日期时都必须编辑代码。我创建了一个称为“日期”的向量,并尝试运行以下代码。
library(httr)
library(jsonlite)
date=c("201801","201802","201803","201804","201805")
for(i in 1:5){
url="https://website.com/api/data"
body=list(fields=list("symbol", "letter", "number"),
history=date[i])
response=POST(url, body=body, encode="json")
data=content(response)$data #data is a portion of the response#
write.csv(data[[i]], paste(i, ".csv"))
}
请注意,如果我消除了for循环,而只使用日期向量中的一个元素,则可以获得一个日期所需的输出
url="https://website.com/api/data"
body=list(fields=list("symbol", "letter", "number"),
history=date[2])
response=POST(url, body=body, encode="json")
data=content(response)$data #data is a portion of the response#
write.csv(data, '2.csv')
使用for循环会创建一个空响应。关于我要去哪里的任何想法吗?
答案 0 :(得分:0)
您可以像这样使它更具可读性:
library(httr)
library(jsonlite)
library(tidyverse)
date <- c("201801","201802","201803","201804","201805")
url <- "https://website.com/api/data"
# Define function
write_files <- function(date, i) {
body <- list(fields = list("symbol", "letter", "number"),
history = date)
response <- POST(url, body = body, encode = "json")
data <- content(response)$data
write.csv(data, file = i)
}
# Apply function to each element of date
imap(date, write_files)
(您的示例不可复制,因此未经测试)
答案 1 :(得分:0)
如上所述,对于for
或lapply
之类的迭代运行潜在的开放式进程,请考虑让循环使用Sys.sleep(##)
等待进程完成。另外,使用seq_along
可以避免 dates 向量的硬编码计数:
dates = c("201801","201802","201803","201804","201805")
for(i in seq_along(dates)){
url = "https://website.com/api/data"
body = list(fields = list("symbol", "letter", "number"),
history = dates[i])
response = POST(url, body = body, encode = "json")
data = content(response)$data # data is a portion of the response
Sys.sleep(5) # ADJUST SECONDS AS NEEDED
write.csv(data, paste0(dates[i], ".csv"))
}
或者,使用lapply
甚至在将每个csv写入列表以供以后使用之后甚至返回数据:
data_list <- lapply(seq_along(dates), function(i) {
url = "https://website.com/api/data"
body = list(fields = list("symbol", "letter", "number"),
history = dates[i])
response = POST(url, body = body, encode = "json")
data = content(response)$data # data is a portion of the response
Sys.sleep(5) # ADJUST SECONDS AS NEEDED
write.csv(data, paste0(dates[i], ".csv"))
return(data)
})