Search code examples
rif-statementvectorizationr-faq

Why can't R's ifelse statements return vectors?


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?


Solution

  • The documentation for ifelse states:

    ifelse returns a value with the same shape as test which is filled with elements selected from either yes or no depending on whether the element of test is TRUE or FALSE.

    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:

    > ifelse(c(TRUE, FALSE), c(1, 2), c(3, 4))
    [1] 1 4
    

    So ifelse is 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) yes and no arguments.

    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.