首页 > 解决方案 > 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?

标签: r

解决方案


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)


推荐阅读