steef1985
steef1985

Reputation: 17

Convert date of birth to age

I want to convert date of birth to age using the following code

df$age <- round(as.numeric(Sys.Date()-as.Date(df$DOB),format="%d/%m/%y")/365)

The format of DOB is f.e. 11-10-1969.

In the dataframe I see an age of 2012 (instead of 52).

I really dont know what I've done wrong. Can someone help me? Thank you in advance!

Upvotes: 1

Views: 318

Answers (1)

Andrew Brown
Andrew Brown

Reputation: 1065

"11-10-1969" (month day year or day month year) is not an unambiguous date format. To get it properly converted you will need to specify the format argument to as.Date()

Note also that a 4-digit year needs a capital Y in the format string: "%d-%m-%Y" (or "%d/%m/%Y" for /). Sys.Date() is already a Date object, so you don't need the format argument with the /s in it.

> as.numeric(Sys.Date() - as.Date("11-10-1969", format="%d-%m-%Y")) / 365.25
#> [1] 52.56674

EDIT: use 365.25 to approximate leap years per Henry's suggestion in comment

Upvotes: 1

Related Questions