Sequence of dates by each next 15th or last day of month [R]

I have start and end dates as e.g. 03-05-2014 and 01-07-2014. I would like to create a code so that it would output sequences such as next 15th of each month or next end day of the month, in this case 15-05-2014 & 15-06-2014, or 31-05-2014 and 31-06-2014.

I know this would be possible by creating sequence of days and then identifying the particular day (at least for the 1st case) as in seq(1st date, 2nd date, by = "day"), but let's just say that for computational limitations this is not possible - I have to create it for many years and millions of records which need to be grouped as well.

Is there any workaround there?

2 answers

  • answered 2018-01-11 21:05 d.b

    d1 = as.Date("03-05-2014", "%d-%m-%Y")
    d2 = as.Date("01-07-2014", "%d-%m-%Y")
    
    library(lubridate)
    d1_p = round_date(d1, unit = "month")
    d2_p = round_date(d2, unit = "month")    
    mydates = seq.Date(d1_p, d2_p, "months")
    mydates = mydates[mydates < d2_p]
    
    lapply(mydates, function(x) x + 14:15)
    #[[1]]
    #[1] "2014-05-15" "2014-05-16"
    
    #[[2]]
    #[1] "2014-06-15" "2014-06-16"
    
    ceiling_date(mydates, unit = "month") - 1 
    #[1] "2014-05-31" "2014-06-30"
    

  • answered 2018-01-11 21:05 troh

    start <- as.Date("2014-05-03")
    end <- as.Date("2014-07-01")
    
    library(lubridate)
    floor_date(seq(start, end, by = 'month'), unit = "month") + 14
    ceiling_date(seq(start, end, by = 'month'), unit = "month")-1
    

    Sequence by the month and use floor_date from the lubridate package to start at the beginning of the month.