Wrapper function in R

Wrapper functions occur in any programming language, and they just mean that you are "wrapping" one function inside another function that alters how it works in some useful way. When we refer to a "wrapper" function we mean a function that the main purpose of the function is to call some internal function; there may be some alteration or additional computation in the wrapper, but this is sufficiently minor that the original function constitutes the bulk of the computation.

As an example, consider the following wrapper function for the log function in R. One of the drawbacks of the original function is that it does not work properly for negative numeric inputs (it gives NaN with a warning message). We can remedy this by creating a "wrapper" function that turns it into the complex logarithm:

Log <- function(x, base = exp(1)) {
  LOG <- base::log(as.complex(x), base = base)
  if (all(Im(LOG) == 0)) { LOG <- Re(LOG) }
  LOG }

The function Log is a "wrapper" for log that adjusts it so that it will now accept numeric or complex inputs, including negative numeric inputs. In the event that it receives a non-negative numeric or a complex input it gives the same output the original log function. However, if it is given a negative numeric input it gives the complex output that should be returned by the complex logarithm.


Say I want to use mean() but I want to set some default arguments and my usecase doesn't allow me to add additional arguments when I'm actually calling mean().

I could create a wrapper function:

mean_noNA <- function(x) {
    return(mean(x, na.rm = T))
}

mean_noNA is a wrapper for mean() where we have set na.rm to TRUE.

Now we could use mean_noNA(x) the same as mean(x, na.rm = T).

Tags:

R

Wrapper