Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the ifelse function return only the first element of a vector provided as an argument?

Tags:

r

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?

like image 535
Hugo Avatar asked Oct 21 '25 17:10

Hugo


1 Answers

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"
like image 141
Jon Spring Avatar answered Oct 23 '25 05:10

Jon Spring



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!