October 2011
Beginner to intermediate
400 pages
9h 30m
English
Suppose we wish to test whether two vectors are equal. The naive approach, using ==, won’t work.
> x <- 1:3 > y <- c(1,3,4) > x == y [1] TRUE FALSE FALSE
What happened? The key point is that we are dealing with vectorization. Just like almost anything else in R, == is a function.
> "=="(3,2) [1] FALSE > i <- 2 > "=="(i,2) [1] TRUE
In fact, == is a vectorized function. The expression x == y applies the function ==() to the elements of x and y. yielding a vector of Boolean values.
What can be done instead? One option is to work with the vectorized nature of ==, applying the function all():
> x <- 1:3 > y <- c(1,3,4) > x == y [1] TRUE FALSE FALSE > all(x == y) [1] FALSE
Applying all() to the result of == asks whether all of the ...
Read now
Unlock full access