Creating a new date variable based on other date variables

Hi- I am trying to create a date variable from two other date variables. Basically, I merged two separate datasets that both had a different named date variable, but I want to merge them into one variable that has either the non-missing date or the earlier date.

Here is an the minimally reproducible example:

MRE_date1 <- as.Date(c("2001-01-01", NA, "2002-01-01", "2003-01-01"))
MRE_date2 <- as.Date(c(NA, "2003-01-01", NA, "2001-01-01"))

MRE <- data.frame(MRE_date1, MRE_date2)
MRE

So, I want to create a new variable (MRE_finaldate) that is either the non-missing date or the earlier date. In this case MRE_finaldate would be: 2001-01-01, 2003-01-01, 2002-01-01, 2001-01-01. However, my working dataset is too large to do this manually. Does anyone know how I can produce a code that does this?

Thank you!!!

Here is one method. It takes advantage of the fact that the min() function will return NA if one of the values is NA.

library(tidyverse)
#> Warning: package 'tibble' was built under R version 4.1.2

MRE_date1 <- as.Date(c("2001-01-01", NA, "2002-01-01", "2003-01-01"))
MRE_date2 <- as.Date(c(NA, "2003-01-01", NA, "2001-01-01"))

MRE <- data.frame(MRE_date1, MRE_date2)
MRE
#>    MRE_date1  MRE_date2
#> 1 2001-01-01       <NA>
#> 2       <NA> 2003-01-01
#> 3 2002-01-01       <NA>
#> 4 2003-01-01 2001-01-01
MRE <- MRE |> rowwise() |> mutate(FinalDate = coalesce(min(MRE_date1, MRE_date2),
                                          MRE_date1, MRE_date2))
MRE                     
#> # A tibble: 4 x 3
#> # Rowwise: 
#>   MRE_date1  MRE_date2  FinalDate 
#>   <date>     <date>     <date>    
#> 1 2001-01-01 NA         2001-01-01
#> 2 NA         2003-01-01 2003-01-01
#> 3 2002-01-01 NA         2002-01-01
#> 4 2003-01-01 2001-01-01 2001-01-01

Created on 2022-03-09 by the reprex package (v2.0.1)

1 Like

Thank you so much! This worked!!!

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.