Skip to content

Instantly share code, notes, and snippets.

@mmparker
Created October 20, 2014 23:55
Show Gist options
  • Select an option

  • Save mmparker/64c9102f7b92c52bb356 to your computer and use it in GitHub Desktop.

Select an option

Save mmparker/64c9102f7b92c52bb356 to your computer and use it in GitHub Desktop.
== vs. %in%
# 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