Quick tip

How to remove elements that are not in a list

It is easy to verify if elements are within a list using the %in% operator in R. For example:

c("a", "b") %in% letters[1:5]
## [1] TRUE TRUE

However, I am often in a situation where I need to do the opposite. This can be easily achieved using the Negate() function.

`%ni%` <- Negate(`%in%`)
c("a", "b") %ni% letters[1:5]

VoilĂ !