Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of months between two dates

Tags:

date

r

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 MathWorks months function

like image 280
knguyen Avatar asked Jan 03 '10 19:01

knguyen


People also ask

How do I find the exact number of months between two dates in Excel?

To find the number of months or days between two dates, type into a new cell: =DATEDIF(A1,B1,”M”) for months or =DATEDIF(A1,B1,”D”) for days.

How do I calculate months between two dates in Excel without Datedif?

Another method to get the number of months between two specified dates is by using the YEARFRAC function. The YEARFRAC function will take a start date and end date as input arguments and it will give you the number of years that have passed during these two dates.


1 Answers

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.

like image 158
Dirk Eddelbuettel Avatar answered Sep 18 '22 13:09

Dirk Eddelbuettel