Suppose you have this data (chosen to contain a few potential edge cases). BTW, it's good form to include a sample of your data or data like it in a replicable form. See here: How to make a great R reproducible example
my_data <- data.frame(
date1 = as.Date(c("2020-01-01", "2020-01-01", "2020-01-01", NA, NA), "%Y-%m-%d"),
date2 = as.Date(c("2020-01-02", "2020-01-02", NA, "2020-01-02", NA), "%Y-%m-%d")
)
> my_data
date1 date2
1 2020-01-01 2020-01-02
2 2020-01-01 2020-01-02
3 2020-01-01 <NA>
4 <NA> 2020-01-02
5 <NA> <NA>
Here are a few approaches to do what you asked.
1) In Base R, you can use ifelse
, but it has a troublesome way of converting dates to numbers and takes some work to bring them back. See How to prevent ifelse() from turning Date objects into numeric objects
my_data$base = as.Date(ifelse(is.na(my_data$date1),
as.character(my_data$date2),
as.character(my_data$date1)), "%Y-%m-%d")
2) dplyr
's if_else
doesn't do this, so you can use:
my_data$if_else = dplyr::if_else(is.na(my_data$date1),
my_data$date2,
my_data$date1)
3) dplyr::coalesce
is a nice way of doing this more concisely:
my_data$coalesce = dplyr::coalesce(my_data$date1, my_data$date2)
Output
> my_data
date1 date2 ifelse if_else coalesce
1 2020-01-01 2020-01-02 2020-01-01 2020-01-01 2020-01-01
2 2020-01-01 2020-01-02 2020-01-01 2020-01-01 2020-01-01
3 2020-01-01 <NA> 2020-01-01 2020-01-01 2020-01-01
4 <NA> 2020-01-02 2020-01-02 2020-01-02 2020-01-02
5 <NA> <NA> <NA> <NA> <NA>