Home > Enterprise >  Looping through dates in R
Looping through dates in R

Time:08-27

I'm trying to create a loop for start and end date to run this function:

startdates <- c("2003-10-01", "2004-10-01", "2005-10-01", "2006-10-01", "2007-10-01", 
"2008-10-01", "2009-10-01", 
"2010-10-01", "2011-10-01", "2012-10-01", "2013-10-01", "2014-10-01", "2015-10-01", 
"2016-10-01","2017-10-01", "2018-10-01", "2019-10-01")

enddates <- c("2004-09-30", "2005-09-30", "2006-09-30", "2007-09-30", "2008-09-30", 
"2009-09-30","2010-09-30", "2011-09-30", "2012-09-30", "2013-09-30", "2014-09-30", 
"2015-09-30", "2016-09-30","2017-09-30", "2018-09-30", "2019-09-30", "2020-09-30")

for(i in dates) {
  statsOutput <- FUNCTIONHERE(siteNumber = "xxx",
                                  startDate = startdates,
                                  endDate = enddates)
}

I'm not sure how to set up this loop so that it will take the start date and end date in my vectors (startdates and enddates). I can't list the function I'm using, but it takes a siteNumber, goes into the web to grab data for that site and then uses the startDate and endDate to know which date range to grab.

CodePudding user response:

We could loop over the sequence of either one of those (assuming both have the same length). Use the index to subset the corresponding 'startdates', 'enddates' within the loop and store the output in a list

statsOutput <- vector('list', length(startdates))
for(i in seq_along(startdates)) {
    statsOutput[[i]] <-  FUNCTIONHERE(siteNumber = "xxx",
                                  startDate = startdates[i],
                                  endDate = enddates[i])
}

Or it may be easier with Map

statsOutput <- Map(FUNCTIONHERE, startDate = startdates, endDate = enddates,
         MoreArgs = list(siteNumber = "xxx"))

CodePudding user response:

We will use paste as the function fun to make this executable. Replace that with whatever you have.

out will be a list of the results. If fun creates scalars and you want a vector result replace Map with mapply.

yr <- 2003:2019
st <- paste0(yr, "-01-01")
en <- paste0(yr, "-09-30")
fun <- paste
out <- Map(fun, "xxx", st, en, USE.NAMES = FALSE)
  • Related