Subtracting dates between two variables in R

I would like some help to do a subtraction between the date I choose, which is the dmda variable, and the date in my df database, which in this case is date1.

For example: I chose dmda as 30/06/2021. The dates of date1 is always 28/06.
Note that the last line is ch<-dates[2:7,]. I put this 2 because I want to subtract dmda-date1, that is, 30/06 - 28-06 = 2. Therefore, this value of 2 can vary, as it will depend on the day I choose in my dmda variable. How do I do this aumomatically, so that I don't have to keep changing the number right there in the chvariable?

library(dplyr)
library(lubridate)
library(tidyverse)

#dataset
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"),
       Week= c("Friday","Saturday","Thursday","Friday","Saturday","Wednesday","Thursday","Friday","Monday"),
       DR01 = c(4,1,4,3,3,4,3,6,5), DR02= c(4,2,6,7,3,2,7,4,3),DR03= c(9,5,4,3,3,2,1,5,5),
       DR04 = c(5,4,3,3,6,2,1,9,5),DR05 = c(5,4,5,3,6,2,1,9,4),
       DR06 = c(2,4,3,3,5,6,7,8,5),DR07 = c(2,5,4,4,9,4,7,8,5)),
  class = "data.frame", row.names = c(NA, -9L))

#Generate graph

dmda<-"2021-06-30"

datas<-df %>%
  filter(date2 == ymd(dmda)) %>%
  summarize(across(starts_with("DR"), sum)) %>%
  pivot_longer(everything(), names_pattern = "DR(.+)", values_to = "val") %>%
  mutate(name = as.numeric(name))

ch<-datas[2:7,]
suppressPackageStartupMessages({
  library(lubridate)
})

# dataset
df. <- data.frame(
  date1 = ymd(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 = ymd(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")),
  Week = c("Friday", "Saturday", "Thursday", "Friday", "Saturday", 
           "Wednesday", "Thursday", "Friday", "Monday"),
  DR01 = c(4, 1, 4, 3, 3, 4, 3, 6, 5), DR02 = c(4, 2, 6, 7, 3, 2, 7, 4, 3), 
  DR03 = c(9, 5, 4, 3, 3, 2, 1, 5, 5),
  DR04 = c(5, 4, 3, 3, 6, 2, 1, 9, 5), DR05 = c(5, 4, 5, 3, 6, 2, 1, 9, 4),
  DR06 = c(2, 4, 3, 3, 5, 6, 7, 8, 5), DR07 = c(2, 5, 4, 4, 9, 4, 7, 8, 5)
)

# Generate graph

dmda <- ymd("2021-06-30")
wday(dmda, label = TRUE, abbr = FALSE)
#> [1] Wednesday
#> 7 Levels: Sunday < Monday < Tuesday < Wednesday < Thursday < ... < Saturday
df.[1][[1]] - dmda
#> Time differences in days
#> [1] -2 -2 -2 -2 -2 -2 -2 -2 -2

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.