Skip to content
Prev 200520 / 398503 Next

One basic question - combining two conditions

On 17-Nov-09 08:26:13, Julia Cains wrote:
You can do it by using "&" to express "and". But also be careful
how you lay out an "if ... else ...":

  if (x >= 42) & (x<48) { z = 45 } else 
  if (x >= 48) & (x<60) z = 14

See ?"&" [note the quotes] for general information on the logical
operators, and see ?Control for information about if, if .. else,
and so on.

The point about the layout of "if ... else ..." is that the first
line of

  if (x >= 42) & (x<48) { z = 45 }
  else if (x >= 48) & (x<60) z = 14

is a complete statement, so will be evaluated without looking
any further. Therefore the second line will be interpreted as
a syntax error, since a stand-alone statement cannot begin
with "else" ("else" needs a matching "if" preceding it; but
that has already been swallowed because the first line was
a complete statement). Putting the "else" in the same line
as the "if" means that R knows it is there before executing
the "if".

Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 17-Nov-09                                       Time: 09:15:11
------------------------------ XFMail ------------------------------