For an arbitrary function
f <- function(x, y = 3){
z <- x + y
z^2
}
I want to be able take the argument names of f
> argument_names(f)
[1] "x" "y"
Is this possible?
For an arbitrary function
f <- function(x, y = 3){
z <- x + y
z^2
}
I want to be able take the argument names of f
> argument_names(f)
[1] "x" "y"
Is this possible?
formalArgs
andformals
are two functions that would be useful in this case. If you just want the parameter names thenformalArgs
will be more useful as it just gives the names and ignores any defaults.formals
gives a list as the output and provides the parameter name as the name of the element in the list and the default as the value of the element.My first inclination was to just suggest
formals
and if you just wanted the names of the parameters you could use names likenames(formals(f))
. TheformalArgs
function just is a wrapper that does that for you so either way works.Edit: Note that technically primitive functions don't have "formals" so this method will return NULL if used on primitives. A way around that is to first wrap the function in
args
before passing toformalArgs
. This works regardless of it the function is primitive or not.