Updated age calculation function

I had previously posted a function for calculating age with two dates. This was for the whole number ‘age’ where we are assuming you don’t want someone to be recorded as ’18’ until their 18th birthday (so more than just YEAR – YEAR).

There was an error in the code when a certain combination was entered, so I’ve rewritten it, and this combination (with leap years) is now working correctly.

Code is available here: https://raw.github.com/nzcoops/r-code/master/age_function.R

require(RCurl)

source(textConnection(getURL(“https://raw.github.com/nzcoops/r-code/master/age_function.R”)))

dob <- as.Date(“2000-02-29”)

dov <- as.Date(“2004-02-28”)

age_years(dob, dov)

dob <- as.Date(“2000-02-29”)

dov <- as.Date(“2004-02-29”)

age_years(dob, dov)

dob <- as.Date(“2000-02-29”)

dov <- as.Date(“2004-03-01”)

age_years(dob, dov)

Returns

> dob <- as.Date(“2000-02-29”)
> dov <- as.Date(“2004-02-28”)
> age_years(dob, dov)
[1] 3
> dob <- as.Date(“2000-02-29”)
> dov <- as.Date(“2004-02-29”)
> age_years(dob, dov)
[1] 4
> dob <- as.Date(“2000-02-29”)
> dov <- as.Date(“2004-03-01”)
> age_years(dob, dov)
[1] 4

 

 

 

Calculating Age

Both ‘first’ and ‘second’ need to be date vectors. This is to achieve a calculation of age rounded DOWN in the same way that we say our age (as in we say 17, right up until the day we turn 18). round(x,0) will round up, floor(x) will also cause issues, if the two dates are the same day of the same month but on different years.

EDIT: This had an error and has been superseded by this post.