monkeyshines - 1 year ago 105

R Question

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 best way to do this?

Answer Source

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.