How do I calculate the difference between two dates in months in R?
Suppose both dates:
x <- as.Date("2014-01-07")
y <- as.Date("2015-03-17")
I can easily calculate in seconds, minutes, hours, etc. using the difftime
function.
But it does not take months: (
With the following functions I was able to calculate, but they do not return fractions of months, like difftime
.
monthdiff <- function(x, y){
x <- c(str_sub(x, 1, 4), str_sub(x, 5))
y <- c(str_sub(y, 1, 4), str_sub(y, 5))
12*(x[1]-y[1]) + (x[2] - y[2])
}
criar_anomes <- function(x){
sprintf("%4d%02d", year(x), month(x))
}
So I get:
library(lubridate)
monthdiff(criar_anomes(y), criar_anomes(x))
[1] 14
In addition to a way to return the fraction (in this case should be something with 14.33 guess) months, I would like a more elegant way.