[R] Can you recover default argument values of a function?
Gabor Grothendieck
ggrothendieck at gmail.com
Wed Dec 26 23:21:46 CET 2007
If the default value is a constant such as in
f <- function(x = 1) x
then formals(f)[[1]] will give it to you but it could be an expression
referring to other variables (other arguments, other variables in
the function, free variables) such as
f <- function(x = u, u) x
or
f <- function(x = u+v+w, u) { v <- u+1; x }
in which case you would get an object of class
"name" in the first case or "call" in the second.
On Dec 26, 2007 4:42 PM, Talbot Katz <topkatz at msn.com> wrote:
>
> Hi.
>
> Maybe this is a stupid question. If so, I apologize, but here goes. Suppose I have a function f1(x,...) that calls a function f2(y1,y2,...,yn) in the following way: if x satisfies a certain condition, then I want to call f2(x,y2,...,yn); otherwise I want to use the default value of y1, if there is one. I could do something like the following:
>
> v <- ifelse ( is.null(x), f2( , y2,..., yn), f2( x, y2,..., yn) )
>
> but I'm doing this in a loop (where the y2,...,yn variables may change), and I'd prefer not to execute the ifelse statement each time, so I'd like an initial pre-loop ifelse such as the following:
>
> y0 <- ifelse ( is.null(x), default(y1), x )
>
> where default(y1) is the default value of the y1 argument of f2. Then, inside the loop I'd have
>
> v <- f2( y0, y2,..., yn )
>
> Is there any mechanism that tells me how many arguments a function has, and the default values of each one, if there are default values?
>
> Thanks!
>
> -- TMK --212-460-5430 home917-656-5351 cell
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list