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")