[R] question about difference in date objects

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon Nov 2 12:49:37 CET 2009


On Mon, 2 Nov 2009, Phil Smith wrote:

> Hi R Community:
>
> I want to take the difference in two dates:
>
> dt2 - dt1.
>
> But, I want the answer in months between those 2 dates.
>
> Can you advise me?

How long is a month?

difftime() can give you an answer in days, which might suffice if you 
define a month as a number of days.  Another idea is to use (untested)

getMonth <- function(x)
{
    xx <- as.POSIXlt(x)
    12*xx$year + xx$mon + (xx$mday-1)/31
}

which will convert to a (fractional) number of months since 
1900-01-01, and that can be differenced.

> Please respond to: pzs6 at cdc.gov
>
> Thank you!
> Phil Smith
> Centers for Disease Control and Prevention

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