Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...