Getting arguments of a parent function in R with names

I am trying to write a function that captures the arguments of the function from which it is called. For example,

get_args <- function () as.list( sys.call(sys.parent()) )[-1] caller <- function (x, y, z) { get_args() } caller(1,2,3) [[1]] [1] 1 [[2]] [1] 2 [[3]] [1] 3 

sys.call (), unfortunately, does not add matching parameter names with argument values, and I would like to write a similar version of get_args that returns output similar to

 caller2 <- function (x, y, z) { as.list( match.call() )[-1] } caller2(1,2,3) $x [1] 1 $y [1] 2 $z [1] 3 

replacing get_args () with match.call () is not directly the solution I'm looking for, since in reality get_args will do some other things before returning the arguments to the parent functions.

I tried using match.call () with sys.parent () in several ways, but I cannot get the function to return the arguments of the caller; it just returns get_args () arguments.

Is there a way to make get_args () return an output identical to the output of caller2 for the above test case? I know that manually assigning arguments is possible using formals (), but is this guaranteed to be equivalent?

If any clarification is necessary, leave a comment below. Thanks.

EDIT 1:

The purpose of get_args () is to act as a convenient way to get the arguments with which the function was called. Typing as.list (match.call ()) [- 1] is getting older, but since match.call captures the closest function call, it just gets get_args () arguments at the moment.

get_args () will also receive default arguments from the parent function, but this is easy to implement.

DECISION:

thanks Hong Ooi, the key to using match.call seems to provide both a call and a definition of the function you want to know about. A slightly modified, anonymous version of get_args below for posterity

 get_args <- function () { as.list( match.call( def = sys.function( -1 ), call = sys.call(-1)) )[-1] } 

This version finds the function further in the call stack, captures its definition and call, and maps the parameters to the arguments.

+6
r
source share
1 answer
 get_args <- function() { cl <- sys.call(-1) f <- get(as.character(cl[[1]]), mode="function", sys.frame(-2)) cl <- match.call(definition=f, call=cl) as.list(cl)[-1] } 

The key here is to set the definition argument to match.call as a function of calling get_arg . This should (hopefully!) Work in the general case where get_args can be called from anywhere.

+8
source share

All Articles