简体   繁体   中英

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 eg

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.

%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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM