【发布时间】:2016-07-31 03:52:32
【问题描述】:
使用Lubridate 包,我如何确定两次之间的数字年龄,考虑闰年。
我需要一个函数,用户可以在其中指定年龄的所有单位,例如“毫秒”、“秒”、“分钟”、“周”、“月”和“年”。
这是我到目前为止所得到的说明:
age <- function(from, to = today(), units = "years", floor = FALSE) {
calc = interval(from,to) / duration(num = 1, units = units)
if (floor) calc = as.integer(floor(calc))
calc
}
2016 年是闰年,让我们确定 6 月份开始和结束时间之间的年龄。应该是 30 天。
require(lubridate)
#Consider month of June 2016, known to have 30 days
from = as.POSIXct("2016-6-1")
to = from + months(1)
daysInYear = 365 + leap_year(to)
age(from,to,units='days') #30.00, CORRECT
age(from,to,units='years')*daysInYear #30.08, INCORRECT
age(from,to,units='years')*365 #30.00, CORRECT ANSWER, WRONG DAYS IN YEAR
如果我以“年”计算相同的间隔,它会返回:0.08219178,这是不正确的,因为年龄函数中的持续时间除数没有考虑到 2016 年是闰年,我需要它来计算 @ 987654326@,即相同的值乘以 (365/366)。
有没有更简单的方法来确定两个日期之间的确切数字年龄,考虑闰年,并允许完全指定间隔单位?
【问题讨论】:
-
diff.Date应该考虑闰年。你在哪里证明它没有这样做? -
我没有使用 diff.Date,证据在我上面的例子中。