Testing Vector Equality
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 ...
Get The Art of R Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.