How can I get the formals (arguments) from a call object? formals() only seems to work with functions.
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.
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.
"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).
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.
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)...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With