Frank E Harrell Jr
2009-Jul-24 22:35 UTC
[R] Most elegant way to use formals() in building functions
Dear Group:
I want to create a function having a ... argument and to have the
default arguments evaluated, as thus:
g <- function(a, b, ...) a+b
formals(g) <- alist(a=,b=2+3,...=)
g
function (a, b = 2 + 3, ...)
a + b
But I want the default argument for b to be evaluated as 5. How can
this be done? Note: My real need is for a more complex expression to be
evaluated for the default value of an argument.
I can use formals(g) <- list(a=NULL, b=2+3, ...=NULL) but then list(...)
doesn't behave properly in the function.
Thanks
Frank
--
Frank E Harrell Jr Professor and Chair School of Medicine
Department of Biostatistics Vanderbilt University
Duncan Murdoch
2009-Jul-24 22:47 UTC
[R] Most elegant way to use formals() in building functions
On 24/07/2009 6:35 PM, Frank E Harrell Jr wrote:> Dear Group: > > I want to create a function having a ... argument and to have the > default arguments evaluated, as thus: > > g <- function(a, b, ...) a+b > formals(g) <- alist(a=,b=2+3,...=) > g > function (a, b = 2 + 3, ...) > a + b > > But I want the default argument for b to be evaluated as 5. How can > this be done? Note: My real need is for a more complex expression to be > evaluated for the default value of an argument. > > I can use formals(g) <- list(a=NULL, b=2+3, ...=NULL) but then list(...) > doesn't behave properly in the function.Not sure if it's "most elegant", but I think this works: formals(g) <- eval(substitute(alist(a=,b=default,...=), list(default=2+3))) Duncan Murdoch