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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With