I’m ‘not in’ right now…

Checking whether an item is in a vector or not in a vector is a common task. The notation in R is a little inelegant when expressing the “not in” condition since the negation operator (!) is separated from the comparison operator (%in%):

5 %in% c(1, 2, 3, 4, 5)  # TRUE
!5 %in% c(1, 2, 3, 4, 5) # FALSE

R is a language where you can easily extend the set of built in operators:

`%!in%` <-
  function(needle, haystack) {
    !(needle %in% haystack)
  }

Now, I can express my intentions reasonably clearly with my new, compact, infix operator %!in%:

5 %in% c(1, 2, 3, 4, 5)  # TRUE
5 %!in% c(1, 2, 3, 4, 5) # FALSE

Moral: bend your tools to your will, not the other way ’round.

3 thoughts on “I’m ‘not in’ right now…”

  1. I think, you have a very valid point here 🙂

    Maybe the Negate function is worth a follow-up post in this particular context, since its definition is also somewhat simple and possibly instructive also for novices, particularly regarding the “…” placeholder.

  2. You’re right, Roman, and another user pointed out the Negate() method as well. In almost all cases when coding, there will be multiple ways to get the same result, possibly with a few pros and cons to each.

    I tend to error on less compact, more expressive-to-a-novice, and less magical coding styles. It’s one of the failings of being a professor. 🙂

  3. An even quicker (and generally safer) implementation is to use the handy base::Negate function:
    `%!in%` <- Negate("%in%")

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.