Ordinarily, the 1st January of any year is assigned to day number 1. Similarly, the 1st February of any year is day number 32. I want to assign the 1st October of any year to day number 1. I have a made a function to do this:
dayNumber <- function(date){
library(lubridate)
date <- as.Date(date)
if(month(date)==10 | month(date)==11 | month(date)==12)
{x <- yday(date) - 273
return(x)}
if(month(date)==1 | month(date)==2 | month(date)==3)
{y <- yday(date) + 91
return(y)}
}
The function seems to work fine for single dates:
dayNumber("2002-10-01")
[1] 1
dayNumber("2013-01-01")
[1] 92
However, when applied to a vector of dates, I get a warning and day numbers are not assigned correctly to all dates:
myDates <- c("2003-11-16", "2007-11-01", "1992-10-11", "1993-11-14", "1995-11-12",
"2002-12-08", "2004-01-25", "2004-12-01", "2002-02-14", "2011-01-21")
dayNumber(myDates)
[1] 47 32 12 45 43 69 -248 63 -228 -252
Warning message:
In if (month(date) == 10 | month(date) == 11 | month(date) == 12) { :
the condition has length > 1 and only the first element will be used
What am I doing wrong here?