[R] date to age

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon Jun 30 20:25:42 CEST 2003


On Mon, 30 Jun 2003, William Briggs wrote:

> I have files which have columns of data that look like this:
> 
> DOB
> 9/27/1964
> ...
> 
> That is, dates in month/day/year format.  When variables like DOB are read
> in, they are converted to factors.

Why?  You can avoid that, of course.

> So, I wrote this to convert from date to age in years:
> 
> age<-function(x)
> {as.numeric(Sys.time()-strptime(as.character(x),format="%m/%d/%Y"))/365.25}
> 
> This isn't very precise or pretty, but it works.
> 
> Does anybody have something better?

Convert to POSIXlt and compare differences in years, months, days etc.
Write an extension to difftime() to handle years and contribute it?

-- 
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