How to Match Functions in R

When using functions as arguments in R, it is sometimes necessary to match functions. This also means that if you have an object with the same name as the function you want to use, this whole construct won’t work. Suppose you had the not-so-smart idea of creating a vector with the relative gain of a couple rounds of poker like this:

> round <- c(0.48,-0.52,1.88)

If you tried to call addPercent() with the FUN argument on this vector, you’d get the following error:

> addPercent(round,FUN=round)
Error in addPercent(round, FUN = round) :
 could not find function "FUN"

Instead of passing the code of the round function, R passes the vector round as the FUN argument. To avoid these kind of problems, you can use a special function, match.fun(), in the body of addPercent(), like this:

addPercent <- function(x, mult = 100, FUN, ...){
 FUN <- match.fun(FUN)
 percent <- FUN(x * mult, ...)
 paste(percent, "%", sep = "")
}

This function will look for a function that matches the name round and copy that code into the FUN argument instead of the vector round. As an added bonus, match.fun() also allows you to use a character object as the argument, so specifying FUN = 'round' now works as well.

All native R functions use match.fun() for this purpose, and it is recommended for you to do the same if you write code that will be used by other people. But passing functions works fine without using match.fun() as well, as long as you use sensible names for the other objects in your workspace.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com