Negated in operator

less than 1 minute read

Using non-membership in R conditionals looks clumsily because of the mandatory parentheses around the whole expression:

if (!(element %in% some_set)) {
    foo(element)
}

There is an easy trick, though - we can define our own “not in” function:

"%!in%" <- function(x, table) {
    match(x, table, nomatch = 0L) == 0L
}

Original expression looks much cleaner now:

if (element %!in% some_set) {
    foo(element)
}

Sure, you might say that the negation ! is hard to spot with gray RStudio display of infix operators and we can use the length of intersect as a condition instead. Still, I find this solution more convenient.

Disclaimer: a quick Internet search shows that I am not the first person ever to think of this solution (not that I expected to, given how simple it is).

Tags:

Categories:

Updated: