lubridate 从函数内的句点中提取对象

lubridate extract object from period inside a function

我发现这个有用的函数 here,可以用来计算年龄(或者只计算两个日期之间花费的时间):

calc_age <- function(birthDate, refDate = Sys.Date()) {


    period <- as.period(new_interval(birthDate, refDate),
                        unit = "year")

    period$year

}

我想通过使 unit 成为函数的参数来改进它,这样我们就可以得到以月、天或 period 对象支持的任何单位为单位的年龄。

我试过这样的事情:

calc_age <- function(birthDate, refDate = Sys.Date(), unit = 'year') {


    period <- as.period(new_interval(birthDate, refDate),
                        unit = unit)

    period$unit

}

但我收到此错误消息:

Error in slot(x, name) : no slot of name "unit" for this object of class "Period"

我认为问题与评估有关,所以我用 enquoquotext 尝试了一些事情,但由于我对函数式编程很陌生,所以我无法做到工作。

感谢您的帮助,抱歉英语不好。

这不是问题link中代码的大改编。

calc_age2 <- function(birthDate, refDate = Sys.Date(), unit = "year"){
  int <- interval(birthDate, refDate)
  period <- as.period(int, unit = unit)
  slot(period, unit)
}

unix 的官方年龄是多少?

calc_age2("1970-01-01")
#[1] 49
calc_age2("1970-01-01", unit = "month")
#[1] 593