Why can't R's ifelse statements return vectors?
The documentation for ifelse
states:
ifelse
returns a value with the same shape astest
which is filled with elements selected from eitheryes
orno
depending on whether the element oftest
isTRUE
orFALSE
.
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.
I bet you want a simple if
statement instead of ifelse
- in R, if
isn't just a control-flow structure, it can return a value:
> if(TRUE) c(1,2) else c(3,4)
[1] 1 2
> if(FALSE) c(1,2) else c(3,4)
[1] 3 4
Note that you can circumvent the problem if you assign the result inside the ifelse
:
ifelse(TRUE, a <- c(1,2), a <- c(3,4))
a
# [1] 1 2
ifelse(FALSE, a <- c(1,2), a <- c(3,4))
a
# [1] 3 4
use `if`, e.g.
> `if`(T,1:3,2:4)
[1] 1 2 3