Change a function's default argument for all calls within a scope

r

Solution

You can change the defaults of a function:

mydnorm <- dnorm
formals(mydnorm)$mean <- 2
> mydnorm
function (x, mean = 2, sd = 1, log = FALSE) 
.External(C_dnorm, x, mean, sd, log)
<environment: namespace:stats>

So using your list:

T_par<-list(mean=7,sd=10)
mydnorm <- dnorm
formals(mydnorm)[names(T_par)] <- T_par
mydnorm
> mydnorm
function (x, mean = 7, sd = 10, log = FALSE) 
  .External(C_dnorm, x, mean, sd, log)
<environment: namespace:stats>

Problem

Suppose you want to change the default values of the arguments of a function (to fix ideas let's use `dnorm`) from `mean=0,sd=1` to `mean=pi,sd=pi` within the scope of another function `foo`. You could do: ``` T_par<-list(mean=pi,sd=pi) x=3 do.call(dnorm,c(list(x),T_par)) ``` but in practice I find that in my application the overhead of using `do.call` is too high. What I would like to do is to create a function `my_dnorm` that would be a copy of `dnorm` except for the default values of the argument which would be set according `T_par` and just call `my_dnorm` instead of `do.call(dnorm,c(list(x),T_par))`. How to do this?

Original source