[R] One basic question - combining two conditions

(Ted Harding) Ted.Harding at manchester.ac.uk
Tue Nov 17 10:15:16 CET 2009


On 17-Nov-09 08:26:13, Julia Cains wrote:
> Dear R helpers
> Suppose I want to use two conditions
> 
> if (x >= 42) and (x<48)
> 
> z = 45
> 
> else 
> 
> if (x>= 48) and (x<60)
> 
> z = 14
> 
> how do use this "and" operator to combine two conditions.
> 
> I am sorry as I know for many of you, this is very basic question
> but I am new to R and trying to learn it as early as possible.
> 
> Extremely sorry for this stupid question.
> Please guide
> Julia
> ************************************************

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 ------------------------------




More information about the R-help mailing list