[R] Time difference in months? (difftime, units)

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Nov 17 16:44:59 CET 2004


On Wed, 17 Nov 2004, Andy Bunn wrote:

> Is there a way to calculate the number of months between dates?
>
> StartDate <- strptime("01 March 1950", "%d %B %Y")
> EventDates <- strptime(c("01 April 1955", "01 July 1980"), "%d %B %Y")
> difftime(EventDates, StartDate)
>
> So, there are 61 months between 01 March 1950 and 01 April 1955. There are
> 364 months between 01 March 1950 and 01 July 1980. What I want is for there
> to be a "months" argument to units in difftime. Anybody have a bright idea?

Ah, but months are of variable length.

> Is there a better way to approach this than difftime?

Pretty easy: convert to POSIXlt, then use something like

12*x$year + x$month

and subtract those.  You could set up a class for "months" and have 
as.months and a `-' method ....

> Thanks in advance, Andy
>
>
>> version
>         _
> platform i386-pc-mingw32
> arch     i386
> os       mingw32
> system   i386, mingw32
> status
> major    2
> minor    0.0
> year     2004
> month    10
> day      04
> language R
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>
>

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