2016-07-31 367 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