change a column from birth date to age in r

后端 未结 7 2058
灰色年华
灰色年华 2020-12-09 17:36

I am using data.table for the first time.

I have a column of about 400,000 ages in my table. I need to convert them from birth dates to ages.

What is the bes

相关标签:
7条回答
  • 2020-12-09 18:10

    From the comments of this blog entry, I found the age_calc function in the eeptools package. It takes care of edge cases (leap years, etc.), checks inputs and looks quite robust.

    library(eeptools)
    x <- as.Date(c("2011-01-01", "1996-02-29"))
    age_calc(x[1],x[2]) # default is age in months
    

    [1] 46.73333 224.83118

    age_calc(x[1],x[2], units = "years") # but you can set it to years
    

    [1] 3.893151 18.731507

    floor(age_calc(x[1],x[2], units = "years"))
    

    [1] 3 18

    For your data

    yourdata$age <- floor(age_calc(yourdata$birthdate, units = "years"))
    

    assuming you want age in integer years.

    0 讨论(0)
提交回复
热议问题