7
How do I calculate the difference between two dates in months on the R?
Suppose the two dates:
x <- as.Date("2014-01-07")
y <- as.Date("2015-03-17")
I can easily calculate in seconds, minutes, hours, etc using the function difftime
.
But she won’t take months :(
With the following functions I was able to calculate, but they do not return fractions of months, such as the 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 that returns the fraction (in this case it should be something with 14,33 I think) of the months, I would like a more elegant way than this.
But how do you want to define the fraction of a month? I wonder why each month has a different amount of days.
– Carlos Cinelli
I hadn’t thought about it! I think divide by 31 is ok
– Daniel Falbel