Home > Enterprise >  Subtracting two dates of same dataset in R
Subtracting two dates of same dataset in R

Time:09-23

I would like to create an X variable, which would be the subtraction between 03/07/2021, which is in my date2, and the day which is in my date1, ie 28/06/2021. Therefore, the result is 5.

 df <- structure(
      list(date1 = c("2021-06-28","2021-06-28","2021-06-28","2021-06-28","2021-06-28",
                     "2021-06-28","2021-06-28","2021-06-28","2021-06-28"),
           date2 = c("2021-04-02","2021-04-03","2021-04-08","2021-04-09","2021-04-10","2021-06-30","2021-07-01","2021-07-02","2021-07-03")),
      class = "data.frame", row.names = c(NA, -9L))

CodePudding user response:

X <- as.Date(df$date2) - as.Date(df$date1)

CodePudding user response:

Are you after a column of the differences between all the dates?

library(dplyr)

df <- df |>
  mutate(across(.cols = everything(), as.Date), x = (date2 - date1))

Changing the columns first to dates would make it easier to plot later, but you can keep them as characters:

df <- df |>
  mutate(x = as.Date(date2) - as.Date(date1))

CodePudding user response:

I would suggest to use the difftime function since it gives control over the units which will be outputted. Further you should convert your data type from chr to date seperatly since there could be a typo which would lead to an error.

df$date1 = as.Date(df$date1)
df$date2 = as.Date(df$date2)
(X = difftime(df$date1,df$date2,units = "days")) #Extra bracket for console output

Output:

Time differences in days

[1] 87 86 81 80 79 -2 -3 -4 -5

  •  Tags:  
  • r
  • Related