获取R函数的参数名称

获取R函数的参数名称

本文介绍了获取R函数的参数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于任意函数

f <- function(x, y = 3){
  z <- x + y
  z^2
}

我希望能够使用f

> argument_names(f)
[1] "x" "y"

这可能吗?

推荐答案

formalArgsformals是在这种情况下有用的两个函数.如果只想使用参数名称,则formalArgs会更有用,因为它仅提供名称而忽略任何默认值. formals提供一个列表作为输出,并提供参数名称作为列表中元素的名称,并提供默认名称作为元素的值.

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

我的第一个倾向是只建议formals,如果您只想要参数的名称,则可以使用names(formals(f))之类的名称. formalArgs函数只是为您执行此操作的包装程序,因此无论哪种方法都可以使用.

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.

请注意,从技术上讲,原始函数不具有形式",因此,如果在原始函数上使用此方法,则将返回NULL.一种解决方法是先将函数包装在args中,然后再传递给formalArgs.无论函数是否为原始函数,此方法均有效.

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"

这篇关于获取R函数的参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 10:58