将包和函数称为另一个函数中的参数

Mik*_*ike 5 r function

我试图找到在R.例如在不同的包的特定函数的方法methods(broom::tidy)将返回所有方法的功能tidy在包中broom。对于我当前的问题,最好将methods函数包含在另一个函数中,如下所示: f1 <- function(x,y){ methods(x::y) }

(我删除了与问题无关的其他代码部分。)但是,当我运行这样的函数时:

f1 <- function(x,y){ methods(x::y)}
f1(broom,tidy)
Run Code Online (Sandbox Code Playgroud)

I get the error

Error in loadNamespace(name) : there is no package called ‘x’

If I try to modify it as to only change the function but keep the package the same I get a similar error :

f2 <- function(y){  methods(broom::y)}
f2(tidy)
Run Code Online (Sandbox Code Playgroud)

Error: 'y' is not an exported object from 'namespace:broom'

How can I get the package and function name to evaluate properly in the function? Does this current issue have to do with when r is trying to evaluate/substitute values in the function?

MrF*_*ick 5

无论是::methods()功能使用非标准的评估,以便工作。这意味着您需要更加聪明地将值传递给函数,以使其正常工作。这是一种方法

f1 <- function(x,y){ 
  do.call("methods", list(substitute(x::y)))
}
f1(broom,tidy)
Run Code Online (Sandbox Code Playgroud)

在这里,我们用于substitute()扩展和,x并将y值传递到名称空间查找中。那解决了::您可以看到的部分

f2 <- function(x,y){ 
  substitute(x::y)
}
f2(broom,tidy)
# broom::tidy
Run Code Online (Sandbox Code Playgroud)

我们需要替代品,因为很可能会有一个x带有功能的包装y。因此,使用时不会扩展变量::。请注意,这::只是一个包装,getExportedValue()否则您需要使用字符值从名称空间中提取值。

但是还有另外一个问题:methods()不评估其参数,它使用原始表达式来找到方法。这意味着我们实际上不需要的值broom::tidy,我们可以传递该文字表达式。由于我们需要评估替代项以获得所需的表达式,因此我们需要使用进行构建,do.call()以评估substitute并将该表达式传递给methods()