Conditional Data Selection

DESCRIPTION:

Return x or y, depending on test. Allows multiple tests.

USAGE:

ifelse1(test, x, y, ...) # actual arguments 
ifelse1(test, x, y)      # usual way to use 
ifelse1(test1, x, test2, v, w) # two conditions 

REQUIRED ARGUMENTS:

test
logical value; if TRUE return x
x
Any object; this is returned if test is TRUE.
y
If there are three arguments, then any object; this is returned if test is FALSE. If there are 5 or more arguments, then a logical value

OPTIONAL ARGUMENTS:

...
There should be 3, 5, 7, etc. arguments to this function; arguments 1, 3, 5, etc. should be logical values; the other arguments (even numbered, and last) are objects that may be returned.

VALUE:

With three arguments, one of x or y. With k arguments, one of arguments 2, 4, ..., k-1, k.

DETAILS:

This is equivalent to {if(test) x else y} . The main advantage of using this function is better formatting, and a more natural syntax when the result is being assigned; see examples below.

With 5 arguments, this is equivalent to {if(test1) x else if(test2) u else v} (where arguments are given by name, not position).

In ifelse1, test should be a single value, and the calculations for y (or x) are not performed if it is not selected. In contrast, for ifelse, test is normally a vector, both x and y are evaluated, even if not used, and x and y are vectors the same length as test.

SEE ALSO:

, .

EXAMPLES:

x <- 1:3; y <- matrix(1:2)  # so example runs 
# Here is code from %*%.default 
  { # must enclose in {}, so example runs 
    if(length(x) == nrow(y)) 
      dim(x) <- c(1, length(x)) 
    else dim(x) <- c(length(x), 1) 
  } 
# Using if ... else ... 
    dim(x) <- { 
      if(length(x) == nrow(y)) 
        c(1, length(x)) 
      else c(length(x), 1) 
    } 
 
# Using ifelse1 
    dim(x) <- ifelse1(length(x) == nrow(y),  
                      c(1, length(x)),  
                      c(length(x), 1))