ℕʘʘḆḽḘ
ℕʘʘḆḽḘ

Reputation: 19375

how to break a time range into monthly queries?

Consider this simple example

bogus <- function(start_time, end_time){
  print(paste('hey this starts on', start_time, 'until', end_time))
}

start_time <- ymd('2018-01-01')
end_time <- ymd('2018-05-01')

> bogus(start_time, end_time)
[1] "hey this starts on 2018-01-01 until 2018-05-01"

Unfortunately, doing so with a long time range does not work with my real-life bogus function, so I need to break my original time range into monthly pieces.

In other words the first call would be bogus(ymd('2018-01-01'), ymd('2018-01-31')), the second one bogus(ymd('2018-02-01'), ymd('2018-02-28')), etc.

Is there a simple way to do using purrr and lubridate? Thanks

Upvotes: 0

Views: 52

Answers (2)

arg0naut91
arg0naut91

Reputation: 14764

Are you looking for something like:

library(lubridate)

seq_dates <- seq(start_time, end_time - 1, by = "month")

lapply(seq_dates, function(x) print(paste('hey this starts on', x, 'until', ceiling_date(x, unit = "month") - 1)))

You could also do a short bogus function like:

bogus <- function(start_var, end_var) {

 require(lubridate)

 seq_dates <- seq(as.Date(start_var), as.Date(end_var) - 1, by = "month")

 printed_statement <- lapply(seq_dates, function(x) paste('hey this starts on', x, 'until', ceiling_date(x, unit = "month") - 1))

 for (i in printed_statement) { print(i) }

}

And call it like:

bogus("2018-01-01", "2018-05-01")

Output:

[1] "hey this starts on 2018-01-01 until 2018-01-31"
[1] "hey this starts on 2018-02-01 until 2018-02-28"
[1] "hey this starts on 2018-03-01 until 2018-03-31"
[1] "hey this starts on 2018-04-01 until 2018-04-30"

This way you can just give minimum start and maximum end date and get everything in-between.

Upvotes: 4

iod
iod

Reputation: 7592

With base:

seqdate<-seq.Date(start_time,end_time,by="1 month")
dateranges<-data.frame(start.dates=seqdate[1:length(seqdate)-1], 
  end.dates=seqdate[2:length(seqdate)]-1)

  start.dates  end.dates
1  2018-01-01 2018-01-31
2  2018-02-01 2018-02-28
3  2018-03-01 2018-03-31
4  2018-04-01 2018-04-30

Upvotes: 3

Related Questions