Site icon R-bloggers

I’m ‘not in’ right now…

[This article was first published on R – William E. J. Doane PhD, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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.

To leave a comment for the author, please follow the link and comment on their blog: R – William E. J. Doane PhD.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.