Previous: Extracting, Replacing, and Generating Up: Recoding Variables Next: Coding and Recoding Variables


Logical Operators

R has an intuitive method for recoding variables, which relies on logical operators that return statements of TRUE and FALSE. A mathematical operator (such as ==, !=, >, >= <, and <=) takes two objects of equal dimensions (scalars, vectors of the same length, matrices with the same number of rows and columns, or similarly dimensioned arrays) and compares every element in the first object to its counterpart in the second object.

For two vectors of five elements, the mathematical operators compare the first element in x to the first element in y, the second to the second and so forth. Thus, a mathematical comparison of x and y returns a vector of five TRUE/FALSE statements. Similarly, for two matrices with 3 rows and 20 columns each, the mathematical operators will return a 5#5 matrix of logical values.

There are additional logical operators which allow you to combine and compare logical statements:

The && (if and only if) and || (either or) operators are used to control the command flow within functions. The && operator returns a TRUE only if every element in the comparison statement is true; the || operator returns a TRUE if any of the elements are true. Unlike the & and | operators, which return arrays of logical values, the && and || operators return only one logical statement irrespective of the dimensions of the objects under consideration. Hence, && and || are logical operators which are not appropriate for recoding variables.



Gary King 2011-11-29