Search code examples
rlubridate

R sequence of dates with lubridate


Hi I'm trying to get a sequence of dates with lubridate

This doesn't work

seq(ymd('2012-04-07'),ymd('2013-03-22'),by=week(1))

the base command

seq(as.Date('2012-04-7'),as.Date('2013-03-22'),'weeks')

does, but I'd like to know if there is an elegant way to do this with lubridate.

EDIT

Please ignore : solved myself so leaving up for posterity only. Happy to have this deleted if necessary.

seq(ymd('2012-04-07'),ymd('2013-03-22'),by='weeks')

Does the trick


Solution

  • ymd is a wrapper to parse date strings and returns a POSIXct object.

    You simply need to use standard terminology described in ?seq.POSIXt (not lubridate) to define weeks

    seq(ymd('2012-04-07'),ymd('2013-03-22'), by = '1 week')
    seq(ymd('2012-04-07'),ymd('2013-03-22'), by = 'weeks')
    

    will works

    as will

    seq(ymd('2012-04-07'),ymd('2013-03-22'), by = '2 week')
    

    You could coerce the lubridate Period class object to a difftime, but that seems rather unnecessary

    seq(ymd('2012-04-07'),ymd('2013-03-22'), by = as.difftime(weeks(1)))