89_Simple
89_Simple

Reputation: 3805

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.

Upvotes: 0

Views: 196

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269654

%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

Upvotes: 1

Related Questions