如何将包含日期对象的多个列与参考日期进行比较,并报告低于该阈值的列总数?

How can I compare multiple columns containing Date object to a reference Date and report the total number of columns below that threshold?

我的问题是我需要将包含日期的多个列与参考列(此处为 ref_date)进行比较,并存储比每行的参考日期 before/smaller 的观测值数量,在一个新列中(我们称之为 count_date)。

特此提供一点样本数据:

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)

我们可以循环 across 'date' 列,用 ref_date 创建一个逻辑向量 (<) 并得到 rowSums 的 TRUE 值return 每行 'count'

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

-输出

  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

基于 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