Hugo
Hugo

Reputation: 63

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

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?

Upvotes: 4

Views: 991

Answers (2)

Jon Spring
Jon Spring

Reputation: 66425

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"

Upvotes: 5

Ronak Shah
Ronak Shah

Reputation: 388907

First you should post data and code as text and not as an image.

Second ifelse is used for vectors (that has length > 1) for scalars (length = 1) use if/else.

if(TRUE) c(2, 3, 4) else 'a'
#[1] 2 3 4

if(FALSE) c(2, 3, 4) else 'a'
#[1] "a"

Upvotes: 2

Related Questions