calculate difference between two dates in months on the R

Asked

Viewed 3,134 times

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.

  • I hadn’t thought about it! I think divide by 31 is ok

2 answers

4


First, without treating fraction of the month, there are some alternatives to pick differences between 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 is worth noting that this is a difference from the calendar month because a difference between January 31 and February 1, by this definition, is one month.

The part of the fraction of the month is more complicated because it depends on the way you define the fraction of a month. If you define in a simple way, like every 30 days or 31 days or every 4 or 5 weeks, then just use your own difftime 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
  • I think at first it is not necessary to convert to Numeric. Without the conversion it is possible to do most of the operations, and the option remains to be change the drive easily.

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
>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.