使用dplyr和lubridate在R中计算两个日期之间的天数差异?

5

想在R中实现类似于SQL的datediff吗?

基本上,我想要在R中进行这个计算。

Delivery Date  Expected Date   Difference 
2022-01-05     2022-01-07         -2 
        
2个回答

6

将列转换为 Date 类型,并使用 difftime

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

或者使用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

4

首先将日期转换为lubridate日期格式:

2022-01-05 将会变成

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接