[英]Difference in days between two dates in R using dplyr and lubridate?
想要在 R 中執行與 datediff 等效的 SQL 嗎?
基本上,我想在 R 中進行這個計算
Delivery Date Expected Date Difference
2022-01-05 2022-01-07 -2
將列轉換為Date
class 並使用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
首先將您的日期更改為 lubridate date: 2022-01-05 將是
date1 <- ymd("2022-01-05")
date2 <- ymd("2022-01-07")
diff_days <- difftime(date2, date1, units="days")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.