Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Get formals from call object

Tags:

r

How can I get the formals (arguments) from a call object? formals() only seems to work with functions.

like image 385
SFun28 Avatar asked Dec 19 '11 05:12

SFun28


People also ask

How do you find arguments in R?

args() function in R Language is used to get the required arguments by a function. It takes function name as arguments and returns the arguments that are required by that function.

What are formals in R?

formals returns the formal argument list of the function specified, as a pairlist , or NULL for a non-function or primitive. The replacement form sets the formals of a function to the list/pairlist on the right hand side, and (potentially) resets the environment of the function.

What are primitive functions in R?

"Primitive functions are only found in the base package, and since they operate at a low level, they can be more efficient (primitive replacement functions don't have to make copies), and can have different rules for argument matching (e.g., switch and call).

When using a function the functions arguments can be specified by?

Because all function arguments have names, they can be specified using their name. Specifying an argument by its name is sometimes useful if a function has many arguments and it may not always be clear which argument is being specified. Here, our function only has one argument so there's no confusion.


1 Answers

Well, a call does not have formals, only actual arguments... The difference being that a function like foo <- function(x, y, ..., z=42) can be called with actual arguments like foo(42, bar=13).

...But getting the arguments can be done like this:

a <- call('foo', a=42, 13)
as.list(a)[-1]
#$a
#[1] 42
#
#[[2]]
#[1] 13

...on the other hand, you can usually (not always) find the actual function and find the formals for it:

a <- quote(which(letters=='g'))
formals(match.fun(a[[1]]))
#$x
#
#$arr.ind
#[1] FALSE
#
#$useNames
#[1] TRUE

Here you'd need to add some error handling if the function can't be found (as with the call to foo above)...

like image 175
Tommy Avatar answered Oct 07 '22 13:10

Tommy