Reputation:
Is there a way to get all function parameters from within a function?
match.call()
doesn't return parameters with defaults set but not overridden. For example:
xf <- function (a, b="Hi", c=TRUE) {
print(as.list(match.call(expand.dots=FALSE)))
}
>xf(3)
[[1]]
xf
$a
[1] 3
I am writing a package with a function that calls an existing function, but I want to be able to set defaults that are not on the existing function. (I was planning on using the list from match.call
, passing it into the other function with do.call
and returning the result.
Update: An interesting issue that relates to S3 methods. I created a new S3 method, and used @Ferdinand.kraft's answer. as.list(environment(), all.names=TRUE)
The all.names argument keeps names starting with a .
in the list. It turns out the the method dispatch adds several arguments to the function environment, including .Generic
.Class
.Method
and several others. This could cause problems if you pass these on to the function in do.call
. One of the other answers may be a better all around solution, but I like the simplicity of as.list(environment())
.
Upvotes: 10
Views: 2669
Reputation: 12829
You can also return the environment at the beginning of the function:
xf <- function (a, b="Hi", c=TRUE) {
as.list(environment(), all=TRUE)
}
Result:
> xf(a=1)
$a
[1] 1
$b
[1] "Hi"
$c
[1] TRUE
Upvotes: 11
Reputation: 115485
You can use ls
and mget
. ls
will (by default), list the objects in the calling frame (in this case, within the function), mget
will get these.
eg
xf <- function(a,b='Hi',c){
# this gets the current definitions of `a`, `b`, and `c`
incall <-mget(ls())
incall}
xf(3)
## $a
## [1] 3
##
## $b
## [1] "Hi"
##
## $c
You can then use do.call(whatever, incall)
Upvotes: 6