r - How to write multiple .csv files based on responses from API that are date dependent
问题描述
I am trying to create csv files that correspond to the response received from an API on a given date.
Instead of having to edit my code each time I want a new date, it seems logical to create a loop. I created a vector called "date", and tried to run the following code.
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"))
}
Note that if I eliminate the for loop and just use an element from the date vector, I get the output desired for one date
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')
Using the for loop creates an empty response. Any ideas as to where I'm going wrong?
解决方案
You can make this a bit more readable like this:
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)
(your example was not reproducible so this is untested)
推荐阅读
- java - 增强Java中数组中元素出现次数最多的方式
- javascript - 如何将基于类的组件中的函数转换为 React 中的函数式组件?
- wordpress - 使用 jQuery 更改文本然后再次更改
- codeigniter-4 - 在 Codeigniter 4 中的路由组内设置自定义错误
- reactjs - React js 基于角色的路由 - 限制未经授权的访问
- android - 如何创建具有动态内容的小部件的长列表,而无需一次又一次地编写相同的代码?
- salt-stack - 冲突键的支柱合并策略
- android - 安卓。确定活动中的第一个片段
- report - Jira Assistant - 跨任务报告的工作日志评论
- ios - 我使用 Getjson IOS 读取在科尔多瓦中存在的文件时得到 404