tags:

views:

211

answers:

2

Hi,

Is there a standard/common method/formula to calculate the number of months between two dates in R?

I am looking for something that is similar to http://www.mathworks.com/access/helpdesk/help/toolbox/finance/months.html

Thanks.

+2  A: 

Hi Khanh,

I was about to say that's simple, but difftime() stops at weeks. How odd.

So one possible answer would be to hack something up:

# turn a date into a 'monthnumber' relative to an origin
R> monnb <- function(d) { lt <- as.POSIXlt(as.Date(d, origin="1900-01-01")); \
                          lt$year*12 + lt$mon } 
# compute a month difference as a difference between two monnb's
R> mondf <- function(d1, d2) { monnb(d2) - monnb(d1) }
# take it for a spin
R> mondf(as.Date("2008-01-01"), Sys.Date())
[1] 24
R> 

Seems about right. One could wrap this into some simple class structure. Or leave it as a hack :)

Edit: Also seems to work with your examples from the Mathworks:

R> mondf("2000-05-31", "2000-06-30")
[1] 1
R> mondf(c("2002-03-31", "2002-04-30", "2002-05-31"), "2002-06-30")
[1] 3 2 1
R> 

Adding the EndOfMonth flag is left as an exercise to the reader :)

Edit 2: Maybe difftime leaves it out as there is no reliable way to express fractional difference which would be consistent with the difftime behavior for other units.

Dirk Eddelbuettel
Thanks, Dirk. That's a clever trick. Speaking of units, I found out that this also works..>as.numeric(as.Date('2009-10-1') - as.Date('2009-8-01'), units = 'weeks')> as.numeric(as.Date('2009-10-1') - as.Date('2009-8-01'), units = 'days')but it stops at 'weeks' as well.
knguyen
I think that is just clever overloading of the - operator to invoke the same `difftime()` function. "No Free Lunch" as the saying goes :)
Dirk Eddelbuettel
+1  A: 

Hi Khan,

there is a message just like yours in the R-Help mailing list (previously I mentioned a CRAN list). Here the link. There are two suggested solutions. best regards, Manoel Galdino

Manoel Galdino
That would be the R-Help mailing list. CRAN is a package repository.
Sharpie