I was puzzled by the result of the following R code:
ifelse(TRUE, c(2, 3, 4), "a")
#[1] 2
The result is 2, but I expected to be 2, 3, 4. Why is this?
From the help ?ifelse:
"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."
I think this is to say that if your test is a vector of length one (like your TRUE) it returns a value of length one too. If the test has a length of two, it'll return a value of length two. (Recycling the elements of the designated value, if necessary.)
> ifelse(TRUE, c(2,3,4), "a")
[1] 2
> ifelse(c(TRUE,TRUE), c(2,3,4), "a")
[1] 2 3
> ifelse(c(FALSE,FALSE), c(2,3,4), "a")
[1] "a" "a"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With