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.
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.
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)
.
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.
© 2022 - 2024 — McMap. All rights reserved.
dir
at the console, and you will see it is just a wrapper forlist.files
, for example. – Voletta