Home > Net >  Difference in days between two dates in R using dplyr and lubridate?
Difference in days between two dates in R using dplyr and lubridate?

Time:01-06

Looking to do the SQL equivalent of datediff in R?

Basically, I want this calculation in R

Delivery Date  Expected Date   Difference 
2022-01-05     2022-01-07         -2 
        

CodePudding user response:

Convert the columns to Date class and use difftime

df1$Difference <-  with(df1, as.numeric(difftime(as.Date(DeliveryDate), 
           as.Date(ExpectedDate), units = "days")))

Or using tidyverse

library(dplyr)
library(lubridate)
df1 %>% 
  mutate(Difference = as.numeric(difftime(ymd(DeliveryDate), 
         ymd(ExpectedDate), units = "days")))
  DeliveryDate ExpectedDate Difference
1   2022-01-05   2022-01-07         -2

CodePudding user response:

First change your date to lubridate date: 2022-01-05 would be

date1 <- ymd("2022-01-05") 
date2 <- ymd("2022-01-07")
diff_days <- difftime(date2, date1, units="days")
  •  Tags:  
  • Related