I’ve found R’s ifelse statements to be pretty handy from time to time. For example:
ifelse(TRUE,1,2)
# [1] 1
ifelse(FALSE,1,2)
# [1] 2
But I’m somewhat confused by the following behavior.
ifelse(TRUE,c(1,2),c(3,4))
# [1] 1
ifelse(FALSE,c(1,2),c(3,4))
# [1] 3
Is this a design choice that’s above my paygrade?
The documentation for
ifelsestates:Since you are passing test values of length 1, you are getting results of length 1. If you pass longer test vectors, you will get longer results:
So
ifelseis intended for the specific purpose of testing a vector of booleans and returning a vector of the same length, filled with elements taken from the (vector)yesandnoarguments.It is a common confusion, because of the function’s name, to use this when really you want just a normal
if () {} else {}construction instead.