VersBersch
VersBersch

Reputation: 193

R function wrapper than maintains function signature

I am trying to write a very simple function wrapper in R, that will accept f and return g where g returns zero whenever the first argument is negative. I have the following code

wrapper <- function(f) {
    function(x, ...) {
        if( x <= 0 ) { 0 }
        else { f(x, ...) }
    }
}

Thge wrapper works as expected, but is there are way to maintain the function signature

> wdnorm <- wrapper(dnorm)

> args(dnorm)
function (x, mean = 0, sd = 1, log = FALSE)
NULL

> args(wdnorm)
function (x, ...)
NULL

I would like to do something like this (but obviously it doesn't work)

args(g) <- args(f)

is this possible in R?

Upvotes: 0

Views: 293

Answers (1)

xosp7tom
xosp7tom

Reputation: 2183

Here is what you want. Tho, do you really need this?

wrapper <- function(f) {
    f2 = function(x) {
        if (x <= 0) { 0 }
        else { do.call(f, as.list( match.call())[-1]) }
    }
    formals(f2) = formals(f)
    f2
}

wdnorm <- wrapper(dnorm)

args(dnorm)
args(wdnorm)

wdnorm(-5)
wdnorm(5)

output

> args(dnorm)
function (x, mean = 0, sd = 1, log = FALSE) 
NULL
> args(wdnorm)
function (x, mean = 0, sd = 1, log = FALSE) 
NULL

> wdnorm(-5)
[1] 0
> wdnorm(5)
[1] 1.48672e-06

Upvotes: 2

Related Questions