Get the argument names of an R function

天大地大妈咪最大 提交于 2019-12-04 16:47:37

问题


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?


回答1:


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"


来源:https://stackoverflow.com/questions/40640322/get-the-argument-names-of-an-r-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!