使用Lubridate
包,如何確定兩次之間的數字年齡,佔閏年。R 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年是閏年,讓確定六月份的開始和結束時間之間的年齡。應該是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年是閏年,我需要它計算0.08196721
,這是相同的值乘以(365/366)。
是否有更簡單的方法來確定兩個日期之間的確切數字年齡,佔閏年,並允許完整規定間隔單位?
'diff.Date'應占閏年。你的證據在哪裏呢? –
另一個愚蠢:[如何更改列從R出生日期到年齡?](http://stackoverflow.com/q/27096485/903061) – Gregor
我沒有使用diff.Date,證據是在我上面的例子。 –