计算R中两个日期的年份差异

Calculate difference in years of two dates in R

我有一个数据框,我想计算两列的年份差异(我们称之为 id "Age")。

我在将它调整到第二个 column.Althoug 的日期时遇到问题,我根据 Sys.Date() 设法做到了:

require(eeptools)
require(ggplot2)
DT$Age<-age_calc(DT$DateBirth, enddate=Sys.Date(), units="years", 
precise=T)

但是,当我将 Sys.Date() 更改为列的名称(称为 DateUpdated)时:

DT<-data.table(Id=c(1,2,3),DateBirth=c("01/01/1990 
","06/05/1980","07/09/2000"),DateUpdated=c("01/01/2019","03/04/2019",
"06/05/2019"),Age=c(29,38,18))

DT[,DateBirth:=as.Date(DateBirth,format= "%d/%m/%Y")]
DT[,DateUpdated:=as.Date(DateUpdated,format= "%d/%m/%Y")]

DT$Age<-age_calc(DT$DateBirth, enddate=DateUpdated, units="years", 
precise=T)

它returns出现以下错误:

Error in age_calc(DT$DateBirth, enddate = DateUpdated, units = 
"years",  : object 'DateUpdated' not found

有人可以给我一些建议吗? 数据:

您需要提供您要将函数应用到的 data.table 的引用

library(eeptools)  
library(data.table)

DT[, new := age_calc(DateBirth, DateUpdated, units="years", precise=T)]  

DT
#   Id  DateBirth DateUpdated Age  new
#1:  1 1990-01-01  2019-01-01  29 29.00
#2:  2 1980-05-06  2019-04-03  38 38.91
#3:  3 2000-09-07  2019-05-06  18 18.66

age_calc(DT$DateBirth, DT$DateUpdated, units="years", precise=T)
#[1] 29.00 38.91 18.66