calculate the difference between two dates in months in the R

7

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.

    
asked by anonymous 10.06.2015 / 22:23

2 answers

4

First, without treating fraction of the month, there are some alternatives to picking up differences between the calendar month. Examples:

x <- as.Date("2014-01-07")
y <- as.Date("2015-03-17")

# criando uma sequência
length(seq(x, y, by = "months")) - 1
[1] 14

# usando o zoo
library(zoo)
(as.yearmon(y) - as.yearmon(x)) * 12
[1] 14

It's worth noting that this is a difference from the calendar month because a difference between January 31 and February 1, by that definition, is one month.

The fraction portion of the month is more complicated because it depends on how you set the fraction of a month. If you define it in a simple way, such as every 30 days or 31 days or every 4 or 5 weeks, then you only have to use difftime itself and divide the result by the corresponding number:

as.numeric(difftime(y, x, units = "days"))/30
[1] 14.46667
as.numeric(difftime(y, x, units = "days"))/31
[1] 14
    
10.06.2015 / 22:51
3

I found the package mondate to do this:

> library(mondate)
> t2 = as.mondate('2015-03-17')
> t1 = as.mondate('2014-01-07')
> t2 - t1
Time difference of 14.32 months
>
    
13.06.2015 / 01:51