Get a list of all functional parameters from within a function

Is there a way to get all the functional parameters inside a function?

match.call() does not return parameters with default values ​​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 default values ​​that are not in the existing function. (I planned to use the list from match.call , passing it to another function using do.call and returning the result.

Update: An interesting issue related to S3 methods. I created a new S3 method and used the answer @ Ferdinand.kraft. as.list(environment(), all.names=TRUE) The all.names argument saves names starting with . in the list. It turns out that sending a method adds a few arguments to the function environment, including .Generic .Class .Method and several others. This can cause problems if you pass them to the do.call function. One of the other answers may be a better solution, but I like the simplicity of as.list(environment()) .

+7
source share
2 answers

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 
+10
source

You can use ls and mget . ls will (by default) list the objects in the calling frame (in this case, inside the function), mget will get them.

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 

Then you can use do.call(whatever, incall)

+4
source

All Articles