I need to calculate the difference in days between two dates in R. The two dates are in different column and I just need to create another column named DAY_DIFFERENCE. Here is a simple structure of my table:
date1 date2 days_diff
2021-09-12 2021-09-13 1
CodePudding user response:
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
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)
CodePudding user response:
You don't need dplyr
. Try difftime()
.
date1 <- "2021-09-12"
date2 <- "2021-09-13"
days_diff <- as.numeric(difftime(date2, date1))
days_diff
# [1] 1