Next: inforead() Up: MacAnova Help File Previous: hypot()   Contents

if

Usage:
if (Logical){cmd;...}
if (Logical){cmd1;...} else {cmd2;...}
if (Logical1){cmd1;...) elseif (Logical2){cmd2;...} [else {cmd3;...}]



Keywords: syntax, control
if(Logical){Statement} allows conditional execution of Statement, an
arbitrarily complex statement or compound statement.  Statement will be
executed if and only if Logical has the value True.  Logical should be a
LOGICAL variable or expression.  A simple example would be
  Cmd> if(min(x) > 0){logx <- log(x);;}

if(Logical){Statement1} else {Statement2} results in Statement1 being
executed when Logical is True, and Statement2 being executed when
Logical is False.  An example would be
  Cmd> if(min(x) > 0){logx <- log(x);;}else{
         error("Illegal non-positive values")}

if(Logical1){Statement1} elseif(Logical2){Statement2} else {Statement3}
executes Statement1 when Logical1 is True, executes Statement2 when
Logical1 is False and Logical2 is True, and executes Statement3 when
both Logical1 and Logical2 are False.  An example would be
  Cmd> if(min(x) > 0){logx < -log(x);;}elseif(max(x) < 0){
            logx <- -log(-x);;}else{
            error("Not all positive and not all negative")}

There can be additional elseif(Logical){Statement} constructs before the
concluding 'else{...}', and the concluding 'else{...}' can be omitted.
The first Statement for which the corresponding Logical is True is
executed.

The value of any of these constructs starting with 'if' is the value of
whichever '{Statement}' is actually executed.  If no value is wanted, it
is good practice to terminate each Statement with ';;' so the value will
be NULL, as in the examples above.  If all the Logicals are False and
there is no concluding 'else{...}', the value is NULL.  For example,
if(2 > 3){ ...}elseif(5 < 4){...} has value NULL.  See below for
examples of how you can the fact that a conditional statement has a
value.  See also topic 'NULL'.

Once a Logical has been found to be True, any subsequent Logicals are
not evaluated and are not even checked for syntactical correctness.

Examples:
  Cmd> if(ismatrix(x)){xinv <- solve(x);;}else {error("not matrix");;}
  Cmd> a <- if(x < 3){1} else {2}# a <- 1 if x < 3 and a <- 2 otherwise
  Cmd> b <- if(x > 0){1} elseif(x < 0){-1} else{0} # b is 1, -1, or 0

Note: Each '{' following 'if(...)', 'elseif(...)' or 'else' must be on
the same line as the preceding 'if', 'elseif' or 'else'; 'elseif' and
'else' must be on the same line as the preceding '}'.  As usual,
however, you can terminate the line with '\', and continue on the next
line as in the following:
  Cmd> if(x<0)\
         {y <- 1;;}\
       else\
         {y <- 2;;}


Gary Oehlert 2003-01-15