[英]Convert decimal month and year into Date
我有一个“十进制月份”和一个年份变量:
df <- data.frame(decimal_month = c(4.75, 5, 5.25), year = c(2011, 2011, 2011))
如何将这些变量转换为Date
? ( "2011-04-22" "2011-05-01" "2011-05-08"
)。 或者至少到一年中的某一天。
您可以使用zoo
package 中的一些不错的功能:
as.yearmon
将十进制月份的年份和floor
转换为 class yearmon
。
然后使用as.Date.yearmon
及其frac
参数将年月强制转换为 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
如果需要,一年中的一天只是format(df$date, "%j")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.