Changing the default argument for all calls within a scope

Suppose you want to change the default values ​​for the arguments of a function (for capturing ideas allows you to use dnorm

) from mean=0,sd=1

to mean=pi,sd=pi

within another function foo

.

You can do:

T_par<-list(mean=pi,sd=pi)
x=3
do.call(dnorm,c(list(x),T_par)) 

      

but in practice I found that in my application the usage overhead is do.call

too high.

What I would like to do is create a function my_dnorm

that will be a copy dnorm

, except for the default values ​​for the argument to be set to match T_par

and just call   my_dnorm

instead do.call(dnorm,c(list(x),T_par))

. How to do it?

+3


source to share


1 answer


You can change the default values ​​for the 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>

      

+6


source







All Articles