Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the argument names of an R function

Tags:

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?

like image 771
landau Avatar asked Nov 16 '16 19:11

landau


People also ask

How do you find the argument of a function 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 the arguments of a function in R?

Arguments are the parameters provided to a function to perform operations in a programming language. In R programming, we can use as many arguments as we want and are separated by a comma. There is no limit on the number of arguments in a function in R.

What are R named arguments?

Arguments are always named when you define a function. When you call a function, you do not have to specify the name of the argument. Arguments are optional; you do not have to specify a value for them.

Can an R function have no arguments?

Functions are defined using the function() directive and are stored as R objects just like anything else. In particular, they are R objects of class “function”. Here's a simple function that takes no arguments and does nothing.


1 Answers

formalArgs and formals are two functions that would be useful in this case. If you just want the parameter names then formalArgs 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.

f <- function(x, y = 3){   z <- x + y   z^2 }  > formalArgs(f) [1] "x" "y" > formals(f) $x   $y [1] 3 

My first inclination was to just suggest formals and if you just wanted the names of the parameters you could use names like names(formals(f)). The formalArgs 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 to formalArgs. This works regardless of it the function is primitive or not.

> # formalArgs will work for non-primitives but not primitives > formalArgs(f) [1] "x" "y" > formalArgs(sum) NULL > # But wrapping the function in args first will work in either case > formalArgs(args(f)) [1] "x" "y" > formalArgs(args(sum)) [1] "..."   "na.rm" 
like image 126
Dason Avatar answered Sep 23 '22 05:09

Dason