Creating New Column/Var for Diff between two Dates Var with tidyverse

I am new to R so I would appreciate assistance and demo for this: I would like to get the difference in days between two columns of Date variables and have the result in a new column. (I have searched websites/youtube demos, but have not found one yet. Based on what I have learned so far, the package Tidyverse is where it is done and that the days parameter could be changed to: hours, minutes, months, and the like). Thank you.

Since this is the first time that I am requesting help from this R Studio Community: how do I get a notification for responses to this? Will I get an alert via email? Thank you.

One possible solution:

#invent data
DF <- data.frame(Date1=as.Date(c("2021-01-03","2021-01-07","2021-01-15")),
       Date1      Date2
1 2021-01-03 2021-01-05
2 2021-01-07 2021-01-15
3 2021-01-15 2021-01-01

#Make a new column
DF <- DF |> mutate(DateDiff = Date2 - Date1)
       Date1      Date2 DateDiff
1 2021-01-03 2021-01-05   2 days
2 2021-01-07 2021-01-15   8 days
3 2021-01-15 2021-01-01 -14 days

Next time you visit there will be an indicator on your profile icon. Usually a beginner-to-intermediate level question attracts an answer within a day, especially if there is an appropriate reproducible minimal example attached to the question. See the FAQ: How to do a minimal reproducible example reprex for beginners.

I have the same general solution as @FJCC with two differences.

  1. I introduce the lubridate package, which is very useful for time calculations (although not needed here) and does a great job of parsing imported data to convert character strings to dates.
  2. I use the subset operator [ in place of dplyr::mutate. Again, same result through a different method. I prefer it because in conjunction with a few other base functions it covers much of what the tidyverse approach does but with less syntax. Personal preference.
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>     date, intersect, setdiff, union
DF <- data.frame(
  Date1 = ymd(c("2021-01-03", "2021-01-07", "2021-01-15")),
  Date2 = ymd(c("2021-01-05", "2021-01-15", "2021-01-01"))
DF$diffdate <- DF$Date2 - DF$Date1

#>        Date1      Date2 diffdate
#> 1 2021-01-03 2021-01-05   2 days
#> 2 2021-01-07 2021-01-15   8 days
#> 3 2021-01-15 2021-01-01 -14 days

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.