Here's a small df:
x <- structure(list(DOB = structure(c(-1689, 2884, 11348, 10449, -1280,
3128), class = "Date"), SU_BIRTH_DATE = structure(c(47482, 2884,
11347, 10449, -1280, 2324), class = "Date")), .Names = c("DOB",
"SU_BIRTH_DATE"), row.names = c(NA, 6L), class = "data.frame")
Looks like:
glimpse(x)
Observations: 6
Variables: 2
$ DOB <date> 1965-05-18, 1977-11-24, 2001-01-26, 1998-08-11, 1966-07-01, 1978-07-26
$ SU_BIRTH_DATE <date> 2100-01-01, 1977-11-24, 2001-01-25, 1998-08-11, 1966-07-01, 1976-05-13
I want to crate a new feature using ifelse()
like so:
test <- x %>%
mutate(NewDOB = ifelse(is.na(DOB), SU_BIRTH_DATE, DOB))
However:
glimpse(test)
Observations: 6
Variables: 3
$ DOB <date> 1965-05-18, 1977-11-24, 2001-01-26, 1998-08-11, 1966-07-01, 1978-07-26
$ SU_BIRTH_DATE <date> 2100-01-01, 1977-11-24, 2001-01-25, 1998-08-11, 1966-07-01, 1976-05-13
$ NewDOB <dbl> -1689, 2884, 11348, 10449, -1280, 3128
The new variable is not a date it's a double. I tried reformatting it back using lubridate ymd():
test <- x %>%
mutate(NewDOB = ifelse(is.na(DOB), SU_BIRTH_DATE, DOB)) %>%
mutate(NewDOB = ymd(NewDOB))
But:
glimpse(test)
Observations: 6
Variables: 3
$ DOB <date> 1965-05-18, 1977-11-24, 2001-01-26, 1998-08-11, 1966-07-01, 1978-07-26
$ SU_BIRTH_DATE <date> 2100-01-01, 1977-11-24, 2001-01-25, 1998-08-11, 1966-07-01, 1976-05-13
$ NewDOB <date> NA, NA, NA, NA, NA, NA
I also tried just as.Date()
instead of ymd which gave an error:
Error in mutate_impl(.data, dots) : Evaluation error: 'origin' must be supplied.
How can I create a new date fature based on the original two date features without losing the date format? Or at least being able to transform it back? In this case since all cases of DOB are not NA I expected the new feature NewDob to have the exact same data as DOB.