Difference in days between two dates in R using dplyr and lubridate?
Asked Answered
R

2

5

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 
        
Ricotta answered 5/1, 2022 at 16:52 Comment(0)
O
7

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
Overactive answered 5/1, 2022 at 16:54 Comment(0)
F
4

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")
Finalism answered 5/1, 2022 at 17:1 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.