1

I'd like to convert in vector mydates the NA in actual date (Sys.Date()) and if the values is a date then do not change anything, but I don't have success using ifelse or if_else of dplyr package. In my example:

# Package
library(dplyr)

# My vector
mydates<-c(NA,NA,NA,"2019-03-14","2020-05-01",NA,NA)

# Using ifelse
mydatescorr1<-ifelse(is.na(mydates)==TRUE,Sys.Date(),mydates)
mydatescorr1

[1] "18771"      "18771"      "18771"      "2019-03-14" "2020-05-01" "18771"      "18771" 

#Using if_else
mydatescorr2<-if_else(is.na(mydates)==TRUE,Sys.Date(),mydates)
mydatescorr2 

Erro: `false` must be a `Date` object, not a character vector.

Please, any help to fix it?

2 Answers 2

2

mydates is a character vector (class(mydates)), so when you return mydates as it is from the else part you are returning character object and not date. You can use -

dplyr::if_else(is.na(mydates), Sys.Date(), as.Date(mydates))

Or without if_else -

mydates <- as.Date(mydates)
mydates[is.na(mydates)] <- Sys.Date()
Sign up to request clarification or add additional context in comments.

Comments

2

How about

tidyr::replace_na(as.Date(mydates), Sys.Date())

? (You still have to convert mydates to a Date type first.) If you wanted you could pipe it:

mydates %>% as.Date() %>% replace_na(Sys.Date())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.