0

I'm puzzled by my example below. This answer might contain the key for me, but I'm missing it. When I run as.Date("1900-01-01") R prints something that looks just like the input:

> as.Date("1920-01-01")
[1] "1920-01-01"

I had hoped to check that inputs were "Dates" and coerce them to be if they were character, and so I wrote this very simple function to learn what was going on

check_date <- function(x){
  ifelse(class(x)=="Date"
                       , x
                       , as.Date(x))
}

But now it seems like I'm getting a numeric value back out:

cdOut <- check_date("1920-01-01")
> cdOut
[1] -18263

What is happening here?

Michael Roswell
  • 1,300
  • 12
  • 31
  • 3
    This is an annoying vagary of `ifelse`, see a [complete explanation here with general alternatives](https://stackoverflow.com/q/6668963/903061). – Gregor Thomas May 03 '23 at 15:03
  • 2
    I would say, this particular case is a good example of where you should be using `if()`, not `ifelse()`. `ifelse()` is designed for working with vectors and modifying parts of them. When you have a length 1 condition, `if(){}else{}` should be preferred. `if(class(x) != "Date") {x <- as.Date(x)} return(x)` would be a more appropriate function body. – Gregor Thomas May 03 '23 at 15:05
  • @GregorThomas, Thanks, both comments are perfect! – Michael Roswell May 03 '23 at 15:06
  • 2
    I'd also mention that `class(x) ==` is a bad way to check class, because objects in R can have multiple classes. This is why many classes have a `is.class()` function. There is no `is.Date()`, so `if(inherits(x, "Date"))` would be good. (Though with `Date` class this isn't likely to cause problems... just general best practice.) – Gregor Thomas May 03 '23 at 15:08

0 Answers0