[英]Why do I get address must be a character error when I call this api using R?
[英]Using call() with namespace address (:: or :::)
我在将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(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)
如果我们改为使用as.call(list(ggplot2::qplot, 1:10))
发生同样的事情。
我正在寻找的是产生调用ggplot2::qplot(1:10)
。
也许
> eval(as.call(list(getFromNamespace("print", "base"), "Hi there")))
[1] "Hi there"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.