Previous: Extracting, Replacing, and Generating | Up: Recoding Variables | Next: Coding and Recoding Variables |
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.
> x <- c(1, 2, 3, 4, 5) # Creates the object `x'. > y <- c(2, 3, 3, 5, 1) # Creates the object `y'. > x == y # Only the 3rd `x' exactly equals [1] FALSE FALSE TRUE FALSE FALSE # its counterpart in `y'.(The = symbol is not a logical operator.)
> x != y [1] TRUE TRUE FALSE TRUE TRUE
> x > y # Only the 5th `x' is greater [1] FALSE FALSE FALSE FALSE TRUE # than its counterpart in `y'. > x >= y # The 3rd `x' is equal to the [1] FALSE FALSE TRUE FALSE TRUE # 3rd `y' and becomes TRUE.
> x < y # The elements 1, 2, and 4 of `x' are [1] TRUE TRUE FALSE TRUE FALSE # less than their counterparts in `y'. > x <= y # The 3rd `x' is equal to the 3rd `y' [1] TRUE TRUE TRUE TRUE FALSE # and becomes TRUE.
There are additional logical operators which allow you to combine and compare logical statements:
> a <- matrix(c(1:12), nrow = 3, ncol = 4) # Creates a matrix `a'. > a [,1] [,2] [,3] [,4] [1,] 1 4 7 10 [2,] 2 5 8 11 [3,] 3 6 9 12 > b <- matrix(c(12:1), nrow = 3, ncol = 4) # Creates a matrix `b'. > b [,1] [,2] [,3] [,4] [1,] 12 9 6 3 [2,] 11 8 5 2 [3,] 10 7 4 1 > v1 <- a > 3 # Creates the matrix `v1' (T/F values). > v2 <- b > 3 # Creates the matrix `v2' (T/F values). > v1 & v2 # Checks if the (i,j) value in `v1' and [,1] [,2] [,3] [,4] # `v2' are both TRUE. Because columns [1,] FALSE TRUE TRUE FALSE # 2-4 of `v1' are TRUE, and columns 1-3 [2,] FALSE TRUE TRUE FALSE # of `var2' are TRUE, columns 2-3 are [3,] FALSE TRUE TRUE FALSE # TRUE here. > (a > 3) & (b > 3) # The same, in one step.For more complex comparisons, parentheses may be necessary to delimit logical statements.
> (a < 3) | (b < 3) # (1,1) and (2,1) in `a' are less [,1] [,2] [,3] [,4] # than 3, and (2,4) and (3,4) in [1,] TRUE FALSE FALSE FALSE # `b' are less than 3; | returns [2,] TRUE FALSE FALSE TRUE # a matrix with `TRUE' in (1,1), [3,] FALSE FALSE FALSE TRUE # (2,1), (2,4), and (3,4).