Search code examples
rdplyrtidyverselubridatedatediff

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


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 
        

Solution

  • 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