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
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.
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:
#test data d1 <- as.Date("01 March 1950", "%d %B %Y") d2 <- as.Date(c("01 April 1955", "01 July 1980"), "%d %B %Y") # calculation round((d2 - d1)/(365.25/12))
seq.Dates like this:as.Date.numeric <- function(x) structure(floor(x+.001), class = "Date") sapply(d2, function(d2) length(seq(d1, as.Date(d2), by = "month")))-1
For me this is what worked:
library(lubridate)
Pagos$Datediff <- (interval((Pagos$Inicio_FechaAlta), (Pagos$Inicio_CobFecha)) %/% months(1))
The output is the number of months between two dates and stored in a column of the Pagos data frame.
You can use as.yearmon() function from zoo package. This function converts a Date type variable to a year-month type variable. You can subtract two year-month type variables and then multiple by 12 to get diff in months as follows:
12 * (as.yearmon(Date1) - as.yearmon(Date2))
Date difference in months
$date1 = '2017-01-20';
$date2 = '2019-01-20';
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$year1 = date('Y', $ts1);
$year2 = date('Y', $ts2);
$month1 = date('m', $ts1);
$month2 = date('m', $ts2);
echo $joining_months = (($year2 - $year1) * 12) + ($month2 - $month1);
Another short and convenient way is this:
day1 <- as.Date('1991/04/12')
day2 <- as.Date('2019/06/10')
round(as.numeric(day2 - day1)/30.42)
[1] 338