Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a vector of all days in a year with R

Tags:

date

r

leap-year

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.

like image 613
JD Long Avatar asked Aug 24 '11 14:08

JD Long


2 Answers

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
R> 

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.

like image 119
Dirk Eddelbuettel Avatar answered Oct 10 '22 12:10

Dirk Eddelbuettel


Using Dirk's guidance I've settled on this:

getDays <- function(year){
     seq(as.Date(paste(year, "-01-01", sep="")), as.Date(paste(year, "-12-31", sep="")), by="+1 day")
}
like image 31
JD Long Avatar answered Oct 10 '22 13:10

JD Long