Question

In base R, there are two quite similar ways to work with conditional statements. One is if(condition) .... else .... and the second is ifelse(condition, TRUE Action, FALSE action).

The difference between the two is that the first one works with scalars whereas second one works with vector also?

Answer

Yes, the difference between the two is that the first one works with scalars whereas second one works with vector also. When you use the first one i.e. if(condition) ..... else ..... on a vector you will see a warning message. Let’s say for example, you want to find out which numbers in a vector are divisible by 5:

x = c(5,4,3,5,1,10,2)
if(x%%5==0) TRUE else FALSE
## Warning in if (x%%5 == 0) TRUE else FALSE: the condition has length > 1 and
## only the first element will be used
## [1] TRUE

As you can see in the warning message, the condition is only evaluated based on the first element of vector which turned out to be TRUE. The if only works with single TRUE and FALSE, it dosen’t recycle the condition to the same length as the input vector.

If you are working with vectors, ifelse() should be the choice. For example:

x = c(5,4,3,5,1,10,2)
ifelse(x%%5==0, TRUE, FALSE)
## [1]  TRUE FALSE FALSE  TRUE FALSE  TRUE FALSE

References: Advanced R by Hadley Wickham

Thanks for reading. If you like the question, how about some love and coffee: Buy me a coffee