简体   繁体   中英

Convert decimal month and year into Date

I have a 'decimal month' and a year variable:

df <- data.frame(decimal_month = c(4.75, 5, 5.25), year = c(2011, 2011, 2011))

How can I convert these variables to a Date ? ( "2011-04-22" "2011-05-01" "2011-05-08" ). Or at least to day of the year.

You may use some nice functions from the zoo package:

as.yearmon to convert year and floor of the decimal month to class yearmon .

Then use as.Date.yearmon and its frac argument to coerce the year-month to class Date .

library(zoo)
df$date = as.Date(as.yearmon(paste(df$year, floor(df$decimal_month), sep = "-")),
                  frac = df$decimal_month - floor(df$decimal_month))

#       decimal_month year        date
# 1              4.75 2011  2011-04-22
# 2              5.00 2011  2011-05-01
# 3              5.25 2011  2011-05-08 

If desired, day of year is simply format(df$date, "%j")

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