views:

1273

answers:

3

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 1) a bug or 2) a design choice that's above my paygrade?

+9  A: 

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
Nathan Kitchen
Perhaps what you really wanted for the second set of statements was `if (TRUE) c(1,2) else c(3,4)`.
Jonathan Chang
A: 

yeah, I think ifelse() is really designed for when you have a big long vector of tests and want to map each to one of two options. For example, I often do colors for plot() in this way:

plot(x,y, col = ifelse(x>2,  'red', 'blue'))

If you had a big long vector of tests but wanted pairs for outputs, you could use sapply() or plyr's llply() or something, perhaps.

Brendan OConnor
+3  A: 

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
Ken Williams