我有一个数据框,我想计算两列的年差异(我们将其称为id“ Age”)。
我在将其调整为第二列的日期时遇到问题。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)
它返回以下错误:
Error in age_calc(DT$DateBirth, enddate = DateUpdated, units =
"years", : object 'DateUpdated' not found
有人可以给我一些建议吗? 数据:
答案 0 :(得分:2)
您需要引用要将函数应用到的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
OR
age_calc(DT$DateBirth, DT$DateUpdated, units="years", precise=T)
#[1] 29.00 38.91 18.66