Replace missing date by another date

Hi R Studio Community,
Below in dataset, I have date 1 with missing and I would like to replace the missing date by date2 column, if somebody can help me. It is highly appreciate it. Thanks

# replace missing date by another date

data2 <- data.frame(x1 = 1:10,
                   date1 = c("2020-01-25", NA,"2021-03-15",NA,"2021-05-11","2020-06-07","2021-08-08", NA,"2020-10-18", "2021-11-11"),
                   x3 = c(" ", "B", "A", "F","F", " "," ", " "," "," "),
                   date2 = c("2021-01-25", "2022-02-10","2020-03-15","2021-04-09","2020-05-11",NA,"2020-09-08", NA,"2021-05-18", "2020-10-11"),
                   x4 = factor(c("B", "B", "A", "F", "A", "B", "A", "B","A", "B")),
                   stringsAsFactors = FALSE)

E.g. like this:

library(dplyr)
#> Warning: package 'dplyr' was built under R version 4.1.2
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
data2 <- data.frame(x1 = 1:10,
                   date1 = c("2020-01-25", NA,"2021-03-15",NA,"2021-05-11","2020-06-07","2021-08-08", NA,"2020-10-18", "2021-11-11"),
                   x3 = c(" ", "B", "A", "F","F", " "," ", " "," "," "),
                   date2 = c("2021-01-25", "2022-02-10","2020-03-15","2021-04-09","2020-05-11",NA,"2020-09-08", NA,"2021-05-18", "2020-10-11"),
                   x4 = factor(c("B", "B", "A", "F", "A", "B", "A", "B","A", "B")),
                   stringsAsFactors = FALSE) %>%
  print()
#>    x1      date1 x3      date2 x4
#> 1   1 2020-01-25    2021-01-25  B
#> 2   2       <NA>  B 2022-02-10  B
#> 3   3 2021-03-15  A 2020-03-15  A
#> 4   4       <NA>  F 2021-04-09  F
#> 5   5 2021-05-11  F 2020-05-11  A
#> 6   6 2020-06-07          <NA>  B
#> 7   7 2021-08-08    2020-09-08  A
#> 8   8       <NA>          <NA>  B
#> 9   9 2020-10-18    2021-05-18  A
#> 10 10 2021-11-11    2020-10-11  B

data3 <- data2 %>%
  mutate(date1 = ifelse(is.na(date1),date2,date1)) %>%
  print()
#>    x1      date1 x3      date2 x4
#> 1   1 2020-01-25    2021-01-25  B
#> 2   2 2022-02-10  B 2022-02-10  B
#> 3   3 2021-03-15  A 2020-03-15  A
#> 4   4 2021-04-09  F 2021-04-09  F
#> 5   5 2021-05-11  F 2020-05-11  A
#> 6   6 2020-06-07          <NA>  B
#> 7   7 2021-08-08    2020-09-08  A
#> 8   8       <NA>          <NA>  B
#> 9   9 2020-10-18    2021-05-18  A
#> 10 10 2021-11-11    2020-10-11  B
Created on 2022-04-19 by the reprex package (v2.0.1)

Thank you very much HanOostdijk for your help. it was solved.

This topic was automatically closed 7 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.