0

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?

luciano
  • 13,158
  • 36
  • 90
  • 130

2 Answers2

2

You're using if when you should be using ifelse:

dayNumber <- function(date){
  library(lubridate)
  date <- as.Date(date)
  ifelse(month(date)==10 | month(date)==11 | month(date)==12, yday(date) - 273,  
         ifelse(month(date)==1 | month(date)==2 | month(date)==3, yday(date) + 91, NA))
}

dayNumber(myDates)
 [1]  47  32  12  45  43  69 116  63 136 112

You could further simplify your conditions by using %in%:

dayNumber <- function(date){
  library(lubridate)
  date <- as.Date(date)
  ifelse(month(date) %in% 10:12, yday(date) - 273,  
         ifelse(month(date) %in% 1:3, yday(date) + 91, NA))
}
sebastian-c
  • 15,057
  • 3
  • 47
  • 93
2

This should do the same thing:

 date<-as.Date(date)
 (yday(date)) %% 274 + 1 + 90 * (yday(date) < 274)
 [1]  47  32  12  45  43  69 116  63 136 112

Here 274 is the day number of 1st October.

Note that this and the original code ignores the leap years.

Jouni Helske
  • 6,427
  • 29
  • 52