rdataframedateas.date

Subtract a column of dates with other columns in R


PID Sub D1 D2 D3
123 2015-02-26 2018-04-26 2015-02-26 2014-05-29
345 2014-03-11 2019-05-18 NA 2012-08-11
678 2016-01-22 2017-11-20 2016-01-21 NA
987 2020-06-15 NA 2018-08-19 2019-01-15

This is a table that I have where I would like to subtract the dates from the column "Sub" with the columns D1, D2 and D3. the dates have been converted into Date from character using as.Date. I would like the result to be the days between the dates.

Could you please help me out.


Solution

  • library(tidyverse)
    library(lubridate)
    #> 
    #> Attaching package: 'lubridate'
    #> The following objects are masked from 'package:base':
    #> 
    #>     date, intersect, setdiff, union
    
    df <- read_table("PID   Sub D1  D2  D3
    123 2015-02-26  2018-04-26  2015-02-26  2014-05-29
    345 2014-03-11  2019-05-18  NA  2012-08-11
    678 2016-01-22  2017-11-20  2016-01-21  NA
    987 2020-06-15  NA  2018-08-19  2019-01-15")
    
    df %>% 
      mutate(across(D1:D3, ~ .x - Sub))
    
    #> # A tibble: 4 × 5
    #>     PID Sub        D1        D2        D3       
    #>   <dbl> <date>     <drtn>    <drtn>    <drtn>   
    #> 1   123 2015-02-26 1155 days    0 days -273 days
    #> 2   345 2014-03-11 1894 days   NA days -577 days
    #> 3   678 2016-01-22  668 days   -1 days   NA days
    #> 4   987 2020-06-15   NA days -666 days -517 days
    

    Created on 2022-06-29 by the reprex package (v2.0.1)