Search code examples
rdataframedplyr

ANY function used with dates to return the date/s in R


i have data like so:

Date of Dose 2 episode_1 episode_2 episode_3 episode_4 episode_5
2022-01-15 2022-02-01 2021-12-25 NA 2022-03-01 NA

I need to identify the dates which are 14 days greater than the date of dose 2 from the 5 episode columns. output should be:

Date of BI
2022-02-01, 2022-03-01

what I have tried so far:


vaccine_received_test <- vaccine_received %>%
  rowwise() %>%
  mutate(
    dose_2_plus_14 = `Date of Dose 2` + days(14),
    
    # Check if any episode date is greater than 'Date of Dose 2 + 14 days'
    date_of_BI = case_when(
          any(c(episode_1, episode_2, episode_3, episode_4, episode_5) > dose_2_plus_14, 
          na.rm = TRUE) ~ any(c(episode_1, episode_2, episode_3, episode_4, episode_5), 
          TRUE ~ NA
    )
  )

any ideas on how I can achieve this?


Solution

  • You could pivot, then filter, then pivot:

    library(tidyr)
    library(dplyr)
    
    pivot_longer(df, -1) |>
      filter(value-`Date of Dose 2`>14) |>
      pivot_wider(id_cols=1)
    ___
    # A tibble: 1 × 3
      `Date of Dose 2` episode_1  episode_4 
      <date>           <date>     <date>    
    1 2022-01-15       2022-02-01 2022-03-01
    

    Data:

    df <- structure(list(`Date of Dose 2` = structure(19007, class = "Date"), 
        episode_1 = structure(19024, class = "Date"), episode_2 = structure(18986, class = "Date"), 
        episode_3 = NA, episode_4 = structure(19052, class = "Date"), 
        episode_5 = NA), row.names = c(NA, -1L), class = c("tbl_df", 
    "tbl", "data.frame"))