简体   繁体   English

如何计算 dplyr 中两个日期之间的差异(以天为单位)? R

[英]How do I calculate the difference between two dates in dplyr (in days)? R

I need to calculate the difference in days between two dates in R.我需要计算 R 中两个日期之间的天数差。 The two dates are in different column and I just need to create another column named DAY_DIFFERENCE.这两个日期在不同的列中,我只需要创建另一个名为 DAY_DIFFERENCE 的列。 Here is a simple structure of my table:这是我的表的简单结构:

     date1           date2     days_diff
     2021-09-12    2021-09-13      1
      

this is a possible solution;这是一个可能的解决方案;

date1 <- as.Date("2021-09-12")

date2 <- as.Date("2021-09-13")

datediff <- date2 - date1

If you just want the difference as a number如果您只想将差异作为数字

as.numeric(datediff)

with dplyr与 dplyr

library(dplyr)
df <- data.frame(date1 = c("2021-09-12","2021-09-13"),
                 date2 = c("2021-09-13","2021-10-14"))

df$date1 <- df$date1 %>%
  as.Date()
df$date2 <- df$date2 %>%
  as.Date()

df$datediff <- as.numeric(df$date2 - df$date1)

You don't need dplyr .您不需要dplyr Try difftime() .尝试difftime()

date1 <- "2021-09-12"

date2 <- "2021-09-13"

days_diff <- as.numeric(difftime(date2, date1))

days_diff
# [1] 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM