Say I have a very simple function that checks the value of an and behaves differently depending if it matches one of a number of possibilities. Here's a minimal example:
is_duck <- function(x) {
if (x == 'duck') return("QUACK")
else return("That's not a duck!")
}
This works well enough as long as I behave with what I pass my function. But R is dynamically typed, so it's a lawless land out there. I want x == DUCK
to be a length-1 logical vector which I can throw into my branching logic, but I can't guarantee it will be. Is there a better, more type-safe way to accomplish the behavior I want?
I thought about if(identical(x, 'duck'))
but that would fail in the case that x has some additional attribute, which is a little too specific (i.e., x <- set_names('duck')
would return "That's not a duck!" even though it is). Is isTRUE(x == 'duck')
what I'm looking for?