ifelse(test, yes, no)
The ifelse function is used to assign one object or another depending on whether the first argument, test, is TRUE or FALSE. It even works as one would hope when test is a vector.
  • test – A logical expression, which may be a vector.
  • yes – What to return if test is TRUE.
  • no – What to return if test is FALSE.

Example. Three objects are initialized. The ifelse function will return the corresponding elements from yes for those elements of test that are TRUE, and it will return the value from no for those that are FALSE.
> test <- c(TRUE, FALSE, TRUE, TRUE)
> yes  <- 1:4
> no   <- 0
> ifelse(test, yes, no)
[1] 1 0 3 4
Notice that ifelse recycles the no vector since the test contains more elements than no. ifelse would do the same with yes if that argument also had shorter length than test.
Tip. This function would have been useful for the example presented in the Recall post.

Leave a Reply