Search code examples
rdatelubridate

extract month from a character year and doy in R


Given a year and a day (in Julian day), how can I extract the month? For e.g.

Year <- '2000'
Doy  <- '159'

I want to extract the month for the above Year and Doy. I thought first I will convert this into date and then extract the month out of it using format(mydate,"%m")

# first convert into date and then extract the month  
as.Date(paste0(Year'-',Doy), format = '%Y-%d')
NA

This gives me NA.


Solution

  • %d is for day of month. %j is for day of year where Jan 1 is day of year 1, Jan 2 is day of year 2, ..., Dec 31 is day of year 365 (or 366 on leap years). See ?strptime for the percent codes.

    Year <- '2000'
    Doy  <- '159'
    
    date <- as.Date(paste(Year, Doy), format = "%Y %j"); date
    ## [1] "2000-06-07"
    
    as.numeric(format(date, "%m")) # month number
    ## [1] 6