How to write and document %special% functions in R

November 26, 2016

(This article was first published on Peter Solymos - R related posts, and kindly contributed to R-bloggers)

I spend a considerable time of my working hours with data processing where I often use the %in% R function as x %in% y. Whenever I need the negation of that, I used to write !(x %in% y). Not much of a hassle, but still, wouldn’t it be nicer to have x %notin% y instead? So I decided to code it for my mefa4 package that I maintain primarily to make my data munging time shorter and more efficient. Coding a %special% function was no big deal. But I had to do quite a bit of research and trial-error until I figured out the proper documentation. So here it goes.

The function

The function name needs quotes and exactly two arguments, one for the left and one for the right hand side of the operator in the middle:

"%notin%" <- function(x, table) !(match(x, table, nomatch = 0) > 0)

Let us see what it does:

1:4 %in% 3:5
1:4 %notin% 3:5


We need to export the function, so just add the following entry to the NAMESPACE file:


The Rd file

This is where things get are a bit more interesting. The LaTeX engine needs the percent sign to be escaped (\%) throughout the whole documentation. Also pay close attention to the usage section (x \%notin\% table).

Negated Value Matching
\code{\%notin\%} is the negation of \code{\link{\%in\%}}, 
which returns a logical vector indicating if there is a non-match or not 
for its left operand.
x \%notin\% table
vector or \code{NULL}: the values to be matched.
vector or \code{NULL}: the values to be matched against.
A logical vector, indicating if a non-match was located for each element of 
\code{x}: thus the values are \code{TRUE} or \code{FALSE} and never \code{NA}.
Peter Solymos 
All the opposite of what is written for \code{\link{\%in\%}}.
1:10 \%notin\% c(1,3,5,9)
sstr <- c("c","ab","B","bba","c",NA,"@","bla","a","Ba","\%")
sstr[sstr \%notin\% c(letters, LETTERS)]

To leave a comment for the author, please follow the link and comment on their blog: Peter Solymos - R related posts. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)