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, [EMAIL PROTECTED] 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 ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.