JD Long JD Long - 11 months ago 73
R Question

Get a vector of all days in a year with R

Is there a simple R idiom for getting a vector of the days in a given year? I can do the following which does ok... except for leap years:

dtt <- as.Date( paste( as.character(year), "-1-1", sep="") ) + seq( 0,364 )

I could, obviously, add a line to filter out any values in (year + 1) but I'm guessing there's a much shorter way to do this.

Answer Source

What about this:

R> length(seq( as.Date("2004-01-01"), as.Date("2004-12-31"), by="+1 day"))
[1] 366
R> length(seq( as.Date("2005-01-01"), as.Date("2005-12-31"), by="+1 day"))
[1] 365

This uses nuttin' but base R to compute correctly on dates to give you your vector. If you want higher-level operators, look e.g. at lubridate or even my more rudimentary RcppBDT which wraps parts of the Boost Time_Date library.