3. Logical Operations

Comparison Operators

   <     less than
   >     greater than
   ==    equal to
   !     not
   <=    less than or equal to
   >=    greater than or equal to
   !=    not equal to

> size[,3] > 160
[1] F T F T F                * comparison operators compare data values
                               and return logical values of T (True)
                               when the comparison is true and F (False)
                               when the comparison is false
> size[,1] == 110
[1] T F F F F

Logic Operators

   &     and
   |     or
   xor   exclusive or     (or and only or)
Logic operators are used in conjunction with comparison operators to evaluate more than one logical expression

The following table gives the results for every pair of logical values (TRUE, FALSE, NA), using the &, |, and xor operators. ie.: T & T = T, T & F = F ... Note that the syntax for xor is xor(expression, expression) whereas the syntax for & and | is expression & expression and expression | expression.

         (T T)   (T F)   (F F)   (NA T)   (NA F)   (NA NA)

&          T       F       F       NA        F       NA

|          T       T       F        T       NA       NA

xor        F       T       F       NA       NA       NA

& returns
T when both expressions are T
F when at least one expression is F
NA otherwise
| returns
T when at least one expression is T
F when both expressions are F
NA otherwise
xor returns
T when one expression is T and one is F
F when both expressions are either T or F
NA otherwise
> xor(T & F, T | F)
[1] T

> xor(T & T, T | F)
[1] F
Because of the way numbers are stored in Splus, the results of arithmetic operations are not always what one would expect. This can be a problem when using comparison operators. Try the following expressions.

    x = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 +0.1 + 0.1 + 0.1 + 0.1

> x==1
> print(x,digits = 14)
> x < 1
> x > 1
> trunc(x)
> round(x)
> ceiling(x)
> floor(x)
Logical objects are coerced to numbers when used with functions that require numerical values. When this occurs, TRUE is equivalent to 1 and FALSE is equivalent to 0.

> x_c(1, 2, 3, NA)
> sum(is.na(x)) > 0
[1] T

> x_!is.na(x)
> sum(is.na(x)) > 0
[1] F

> i_!is.na(x)
> i                           * the expression !is.na(x) creates a vector
 [1] T T T T T T T T T F        of logical values: T when x is not a
                                missing value, F when x is missing

Further Reading

Richard A. Becker, John M. Chambers, Allan R. Wilks, The New S Language. A Programming Environmnent for Data Analysis and Graphics, Wadsworth & Brooks/Cole Advanced Books & Software, Pacific Grove, California, 1988, pp. 16, 17, 35, 100

Where to now?

Table of Contents

Simple Statistics