Created
October 20, 2014 23:55
-
-
Save mmparker/64c9102f7b92c52bb356 to your computer and use it in GitHub Desktop.
== vs. %in%
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Broadly speaking, it's safer to %in% instead of == when using a logical | |
| # vector in R because R's indexing will return an NA - which is | |
| # probably not the intuitive behavior. Here's what I mean: | |
| x <- c("a", "b", NA, "c") | |
| # Indexing with == | |
| x[x == "a"] | |
| # Compared with %in% | |
| x[x %in% "a"] | |
| # If you compare the logical vectors created by the two | |
| # comparisons, you can see that %in% *doesn't* return | |
| # an NA - which makes it a lot safer for indexing. | |
| x == "a" | |
| x %in% a | |
| # I almost exclusively use %in% for matching - and when | |
| # I need to use ==, I make sure that I explicitly handle | |
| # the NA cases (usually something like x == "a" & !is.na(x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment