Home > Software engineering >  Calculation of time intervals using 'lubridate'
Calculation of time intervals using 'lubridate'

Time:01-18

For statistical reasons, I would like to calculate the following:

date2 - date1 1(day) ; in month.

For the above equation, this shall mean 1 day if date2 == date1. For data, time data is only available for Y,M,D (no HH,MM). The date below is available for demo.

date <- as.POSIXct("2009-03-08")
date2 <- as.POSIXct("2009-03-09")

I would like to get

( (date %--% date2) 1 )/ months(1)

(But this doesn’t work)

( (date %--% date2) 1 )/ days(1) gives me 2 (days). Now, I would like to calculate this value to month. How can I achieve this? Or rather, can I go straightforward, like below equation? ( (date %--% date2) 1 )/ months(1)

CodePudding user response:

First edition (Deprecated)

date %--% date2 is a <Interval>. You cannot add a numeric value to it. Instead, you need to convert it into a <Period>.

(as.period(date %--% date2)   days(1)) / months(1)

# [1] 0.06570842

Update

The above method is not precise because it cannot take months into account. The ideal output should be

(1   1) / 31
# [1] 0.06451613

becasue March has 31 days. The following way is able to consider the differences of days between different months.

(date %--% (date2   days(1))) / months(1)
# [1] 0.06451613

For comparison, we change the dates to February and see the output:

date <- as.POSIXct("2009-02-08")
date2 <- as.POSIXct("2009-02-09")

(date %--% (date2   days(1))) / months(1)
# [1] 0.07142857

which is equal to (1 1)/28.

CodePudding user response:

The difftime command in base R subtracts one date from another. Unfortunately, it does not have the option to return the output in months; however, if we choose days, we can manually convert it.

Base

date1 <- as.POSIXct("2009-03-08")
date2 <- as.POSIXct("2009-03-09")
    
(1   as.numeric(difftime(time1 = date2,time2 = date1,units = "days")))/30.4375

lubridate

library(lubridate)
date1 <- ymd("2009-03-08")
date2 <- ymd("2009-03-09")

(1   as.numeric(date2 - date1))/30.4375

Output

[1] 0.06570842

CodePudding user response:

Please try to divide the 2 dates by 30.4375 which is obtained from 365.25/12

Code

data.frame(date1=date, date2=date2) %>% mutate(date1=as.Date(date1),
                                                        date2=as.Date(date2),
                                                        diff=(date1-date2)/30.4375)
  • Related