Posted by: Dennis | September 16, 2010

Infix functions in R

I couldn’t find all this information in one place on the web so I thought I’d post it here. When writing code, sometimes the standard function syntax for a binary function — e.g. dotproduct(a,b) — is harder to read than the mathematical notation e.g. a.b. In a complicated expression where the function is used many times the latter notation can be much easier to follow. R allows binary functions to take such an form, in which case they are known as infix functions, and they are represented as a keyword surrounded by % characters. Examples are %*% (matrix multiplation) and %in% (test for set membership). This post describes how to define your own infix function and put them in packages.

An infix function is simply defined as a binary function. The trick is that its name must be enclosed in quotes since % is a special character i.e.

"%fun%" <- function(a,b){ ... }

The % character must also be treated differently should you wish to place an infix function in a package, in particular when writing the help file. Typically (i.e. on running package.skeleton), the helpfile is created as z%fun%.Rdata. However this is not an acceptable filename, so change it something else e.g. fun.Rd. Within the .Rd file the % characters must be escaped i.e. replace %fun% everywhere with \%fun\%.

To access the help for an infix function within R, use ?"%fun%". What I can’t work out is how to access an infix function as an object, e.g. to read its R code. Any help welcome!


Responses

  1. “%fun%” <- function(a,b){a+b}
    2%fun%3
    %fun% #error
    `%fun%` #shows definition

    • Brilliant, thanks!


Leave a comment

Categories