【问题标题】:R lubridate, Calculate Age including Leap Years [duplicate]R lubridate,计算包括闰年的年龄[重复]
【发布时间】: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)。

有没有更简单的方法来确定两个日期之间的确切数字年龄,考虑闰年,并允许完全指定间隔单位?

【问题讨论】:

标签: r duration lubridate


【解决方案1】:
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

【讨论】:

  • 既然我们使用的是lubridate,你可以使用lubridate::leap_year()。它与您的相同,但有一些输入检查。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多