[R] Calculate difference between dates in years

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon Sep 24 14:35:47 CEST 2007


On Mon, 24 Sep 2007, Alberto Monteiro wrote:

> Daniel Brewer wrote:
>>
>> I would like to be able to calculate the age of someone at a particular
>> date.  Both dates are date objects.  Here is what I have come up with:
>>
>> floor(as.numeric(sampleInfo$Date.of.DIAGNOSIS-
>> sampleInfo$Date.of.birth)/365.25)
>>
>> Is this the best approach?
>>
> No - leap years and such. You know that there are _not_
> 365.25 days in one year, don't you?
>
> floor(as.numeric(as.Date("2100-02-28") - as.Date("1900-02-28"))/365.25)
> # 199, should be 200
>
> A less extreme counter-example:
>
> floor(as.numeric(as.Date("2008-02-28") - as.Date("2007-02-28"))/365.25)
> # 0, should be 1
>
> Alberto Monteiro (purely destructive - sorry)

You need to convert to broken-down time.  Something like

age_years <- function(from, to)
{
     lt <- as.POSIXlt(c(from, to))
     age <- lt$year[2] - lt$year[1]
     mons <- lt$mon + lt$mday/50
     if(mons[2] < mons[1]) age <- age -1
     age
}

will be fine if used with valid dates (and you could extend it to work 
with date-times).

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list