Comparing 2 date-colums in R

Hello

I need help with comparing 2 columns, both of witch consists of dates.

My dataset consists of 18 patients, all of witch have a medication-date, but only some of them are dead.
What I want to do is to compare the 2 dates (death-date vs medication-date) for the dead patients, and if the medication-date is greater than (>) death-date, then the medication-date has to be changed to be the same date as the deathdate.

  • For those where medication-date is lesser than or same as (<=) death-date, nothing has to be done.
  • For those with no death-date (NA, ie still alive), nothing has to bed done.

I have tried "ifelse", but the result is not correct!

the dput of my dataset is as follows:

structure(list(id= c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18), death = structure(c(NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,16648,172767,17481), class = "Date"), medication = structure(c(17116,17627,17767,17622,17764,17797,17093,17150,17669,17734,17729,17876,18001,17830,17797,15833,17328,17573), class= "Date")), sorted="id", class= c("data.table", "data.frame"), row.names  = c(NA, -18L), .internal.selfref = <pointer: 0x00000000001f1ef0>)

Would appreciate if anyone can help :slight_smile:

Is this what you want to do?

DT <- structure(list(id= c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18), 
               death = structure(c(NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,
                                   NA,NA,16648,172767,17481), 
                                 class = "Date"), 
               medication = structure(c(17116,17627,17767,17622,17764,17797,
                                        17093,17150,17669,17734,17729,17876,
                                        18001,17830,17797,15833,17328,17573), 
                                      class= "Date")), sorted="id", 
          class= c("data.table", "data.frame"), row.names  = c(NA, -18L)) 

tail(DT)
#>    id      death medication
#> 13 13       <NA> 2019-04-15
#> 14 14       <NA> 2018-10-26
#> 15 15       <NA> 2018-09-23
#> 16 16 2015-08-01 2013-05-08
#> 17 17 2443-01-08 2017-06-11
#> 18 18 2017-11-11 2018-02-11
DT$medication <- ifelse(!is.na(DT$death) & DT$death < DT$medication, 
                        DT$death, 
                        DT$medication)
DT$medication <- as.Date(DT$medication, origin = "1970-01-01")
tail(DT)
#>    id      death medication
#> 13 13       <NA> 2019-04-15
#> 14 14       <NA> 2018-10-26
#> 15 15       <NA> 2018-09-23
#> 16 16 2015-08-01 2013-05-08
#> 17 17 2443-01-08 2017-06-11
#> 18 18 2017-11-11 2017-11-11

Created on 2020-04-04 by the reprex package (v0.3.0)

1 Like

@FJCC

This is exactly what I want! Perfect!
Thank you very much :slight_smile:

Perfect brother!

Thank you for the reply. 9apps vidmate

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