Home > database >  How can I compare multiple columns containing Date object to a reference Date and report the total n
How can I compare multiple columns containing Date object to a reference Date and report the total n

Time:03-19

My problem is that I need to compare multiple columns containing Dates, to a reference column (ref_date here) and store the number of observations which are before/smaller than that reference date for each row, in a new column (let's call it count_date).

I hereby provide a little sample data:

ID <- c("1", "2", "3", "4", "5")
date1 <- sample(seq(as.Date('2000/01/01'), Sys.Date(), by="day"), 5)
date2 <- sample(seq(as.Date('2000/01/01'), Sys.Date(), by="day"), 5)
date3 <- sample(seq(as.Date('2000/01/01'), Sys.Date(), by="day"), 5)
ref_date <- sample(seq(as.Date('2000/01/01'), Sys.Date(), by="day"), 5)
count_date <-0
df_test <- data.frame(ID,date1,date2,date3,ref_date,count_date)

CodePudding user response:

We can loop across the 'date' columns, create a logical vector (<) with ref_date and get the rowSums on the TRUE value to return the 'count' per row

library(dplyr)
df_test %>% 
    mutate(count_date = rowSums(across(starts_with('date'), ~ .x < ref_date)))

-output

  ID      date1      date2      date3   ref_date count_date
1  1 2011-02-12 2006-03-11 2013-04-20 2014-07-22          3
2  2 2011-03-27 2008-02-01 2017-07-25 2015-05-29          2
3  3 2011-03-08 2009-11-14 2009-05-26 2012-09-27          3
4  4 2016-11-29 2014-12-20 2007-10-03 2014-10-03          1
5  5 2007-11-27 2011-08-15 2011-07-21 2005-12-12          0

CodePudding user response:

A possible solution in base R:

df_test$count_date <- apply(df_test, 1, \(x) sum(x[2:4] < x[5]))

df_test

#>   ID      date1      date2      date3   ref_date count_date
#> 1  1 2004-10-10 2011-10-02 2018-11-14 2011-11-02          2
#> 2  2 2021-02-13 2021-06-10 2009-12-22 2014-10-24          1
#> 3  3 2001-12-21 2007-06-16 2001-05-24 2015-09-07          3
#> 4  4 2021-05-30 2016-01-07 2016-06-06 2005-12-17          0
#> 5  5 2010-12-06 2021-06-24 2008-03-29 2020-11-01          2
  • Related