Can anyone help me understand what a wrapper function in r is? I would really appreciate if you could explain it with the help of examples on building one's own wrapper function and when to use one.
Thanks in advance.
Wrappers are used for two primary purposes: to convert data to a compatible format or to hide the complexity of the underlying entity using abstraction. Examples include object wrappers, function wrappers, and driver wrappers.
A driver wrapper is a subroutine in a software library that functions as an adapter between an operating system and a driver, such as a device driver, that was not designed for that operating system. It can enable the use of devices for which no drivers for the particular operating system are available.
A wrapper function is a function that mainly calls another function with minimal additional work.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With