2016-07-31 368 views
0

使用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)。

是否有更簡單的方法來確定兩個日期之間的確切數字年齡,佔閏年,並允許完整規定間隔單位?

+0

'diff.Date'應占閏年。你的證據在哪裏呢? –

+0

另一個愚蠢:[如何更改列從R出生日期到年齡?](http://stackoverflow.com/q/27096485/903061) – Gregor

+0

我沒有使用diff.Date,證據是在我上面的例子。 –

回答

0
is.leapyear=function(year){ 
    #http://en.wikipedia.org/wiki/Leap_year 
    return(((year %% 4 == 0) & (year %% 100 != 0)) | (year %% 400 == 0)) 
} 

age.hackr <- 
      function(from, to = today(), units = "years", floor = FALSE) { 
       if(is.leapyear(year(to))){ 
       calc = interval(from,to)/duration(num = 1, units = units) 
       if (floor) calc = as.integer(floor(calc)) 
       calc <- calc - 0.00022457 
       calc 
       } else{ 
       calc = interval(from,to)/duration(num = 1, units = units) 
       if (floor) calc = as.integer(floor(calc)) 
       calc 
       } 
      } 

age.hackr(from, to, units = "years") * 366 

[1] 30

+0

因爲無論如何我們都使用'lubridate',所以你可以使用'lubridate :: leap_year()'。它與你的相同,但有一些輸入檢查。 – Gregor