R 使用命名空间地址为(::或::)的call()

R 使用命名空间地址为(::或::)的call(),r,R,我在使用call()函数以及命名空间地址操作符::和::时遇到问题。在计算调用时,只需将其添加到为call()提供的函数名中,就会产生一个错误,如下例所示: > call("base::print", "Hi there") `base::print`("Hi there") > eval(call("base::print", "Hi there")) Error in `base::print`("Hi there") : could not find function "b

我在使用
call()
函数以及命名空间地址操作符
::
::
时遇到问题。在计算调用时,只需将其添加到为
call()
提供的函数名中,就会产生一个错误,如下例所示:

> call("base::print", "Hi there")
`base::print`("Hi there")
> eval(call("base::print", "Hi there"))
Error in `base::print`("Hi there") : 
 could not find function "base::print"
出于某种原因,
call()
在函数名周围添加了反勾号(可能是因为它包含非标准字符),这似乎把一切都搞糟了。以下是省略“地址”时发生的情况:

> call("print", "Hi there")
print("Hi there")
> eval(call("print", "Hi there"))
[1] "Hi there"
我将非常感谢任何关于如何解决这个问题的建议。但是请注意,我需要使用
call()
生成代码,因为我正在为rmarkdown代码块自动生成代码,并且我需要能够指定名称空间,因为我使用的是包中的未报告函数,我真的希望保持未报告状态

谢谢你的阅读


更新:我忽略了提到我正在寻找的解决方案的另一个属性(我通过阅读下面的Stéphane Laurent的另外一个很好的答案了解到了这一点):我正在寻找一个不将函数定义复制到调用中的解决方案,我相信这排除了使用
get()
的解决方案。作为我试图避免的一个例子,假设我们想从
ggplot2
调用
qplot()
。如果我们使用例如
getFromNamespace()
调用将如下所示(为了便于阅读,省略了输出的中间部分):

as.call(列表(getFromNamespace(“qplot”,“ggplot2”),1:10)) (函数(x,y=NULL,…,数据,facets=NULL,margins=FALSE, geom=“auto”,xlim=c(不适用,不适用),ylim=c(不适用,不适用),log=“”, main=NULL,xlab=deparse(替换(x)),ylab=deparse(替换(y)), asp=NA,stat=NULL,position=NULL) { 如果(!缺失(统计)) 警告(`stat`已弃用),call.=FALSE) 如果(!缺失(位置)) 警告(`position`已弃用),call.=FALSE) 如果(!is.character(geom)) stop(`geom`必须是字符向量),call.=FALSE) 也许吧


虽然对于大多数经验丰富的R用户来说,这个解决方案的工作原理是显而易见的,但最好能简要介绍一下经验较少的用户可以从中学习到什么。谢谢,我不知道
getFromNamespace()
。这很好,但调用会复制到函数定义中。你知道这是否可以避免吗?在我的设置中,这种复制将意味着大量额外的代码行,因为我有时需要调用未报告的函数,例如在同一个rmarkdown文档中调用100次。@AHP不确定是否理解。事实上,你也可以执行
eval(as.call(list(base::print,“Hi there”))
@StéphaneLaurent抱歉,我意识到我的评论不太清楚。我已经尝试在问题的更新中解释了它-我希望这能让它更清楚。
> as.call(list(getFromNamespace("qplot", "ggplot2"), 1:10))

  (function (x, y = NULL, ..., data, facets = NULL, margins = FALSE, 
  geom = "auto", xlim = c(NA, NA), ylim = c(NA, NA), log = "", 
  main = NULL, xlab = deparse(substitute(x)), ylab = deparse(substitute(y)), 
asp = NA, stat = NULL, position = NULL) 
{
  if (!missing(stat)) 
      warning("`stat` is deprecated", call. = FALSE)
  if (!missing(position)) 
      warning("`position` is deprecated", call. = FALSE)
  if (!is.character(geom)) 
      stop("`geom` must be a character vector", call. = FALSE)
  argnames <- names(as.list(match.call(expand.dots = FALSE)[-1]))
  arguments <- as.list(match.call()[-1])
  env <- parent.frame()

#### A lot more code defining the function (omitted)#####

  if (!missing(xlim)) 
      p <- p + xlim(xlim)
  if (!missing(ylim)) 
      p <- p + ylim(ylim)
  p
})(1:10)
> eval(as.call(list(getFromNamespace("print", "base"), "Hi there")))
[1] "Hi there"