![](/img/trans.png)
[英]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.