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
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
case1: naive function
case2: if you need to consider only 'Month' regardless of 'Day'
Example :
There may be a simpler way. It's not a function but it is only one line.
e.g.
Produces:
This calculates the number of whole months between the two dates. Remove the -1 if you want to include the current month/ remainder that isn't a whole month.
I think this is a closer answer to the question asked in terms of parity with MathWorks function
MathWorks months function
My R code
Output (as when the code was run in April 2016)
Lubridate [package] provides tools that make it easier to parse and manipulate dates. These tools are grouped below by common purpose. More information about each function can be found in its help documentation.
interval {lubridate} creates an Interval-class object with the specified start and end dates. If the start date occurs before the end date, the interval will be positive. Otherwise, it will be negative
today {lubridate} The current date
months {Base} Extract the month These are generic functions: the methods for the internal date-time classes are documented here.
%/% {base} indicates integer division AKA ( x %/% y ) (up to rounding error)
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:
seq.Dates
like this: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:
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:
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 thedifftime
behavior for other units.