R名称空间访问和match.fun
我正在处理一个R包,其中一个函数包含对导入到包命名空间的包中的函数的R名称空间访问和match.fun,r,namespaces,package,R,Namespaces,Package,我正在处理一个R包,其中一个函数包含对导入到包命名空间的包中的函数的match.fun调用。但是在加载包时,match.fun调用找不到函数名。我认为我做的一切都是对的,但事实显然并非如此 例如: # in the package file header, for creation of the NAMESPACE via roxygen2: ##` @import topicmodels # The function declaration in the package ModelTopic
match.fun
调用。但是在加载包时,match.fun
调用找不到函数名。我认为我做的一切都是对的,但事实显然并非如此
例如:
# in the package file header, for creation of the NAMESPACE via roxygen2:
##` @import topicmodels
# The function declaration in the package
ModelTopics <- function(doc.term.mat, num.topics, topic.method="LDA"){
topic.fun <- match.fun(topic.method)
output <- topic.fun(doc.term.mat, k=num.topics)
return(output)
}
回答我自己的问题:描述文件在重新还原更新的代码后没有更新
导入:
和依赖:
字段。因此,出现了match.fun
问题。出于好奇,为什么这会影响到match.fun
,而不会影响在别处对导入的包函数进行的一系列其他函数调用 我认为这是一个范围问题。虽然您已经导入了topicmodels
,从而导入了LDA
,但是您还没有导出这些函数,因此它们在搜索路径中不可用
从?match.fun
:
match.fun
不用于顶级,因为它会
在调用方的父级中执行匹配
因此,由于您正在全局环境中使用ModelTopics
,并且LDA
在全局环境中不可用,因此match.fun
调用失败
在我看来,你有两个选择: 选项1:使用
get
另一种方法是使用get
,您可以在其中指定环境。考虑这一点:尝试使用<代码>匹配.Fase在包<代码> GGPROT2:中查找<代码> Prime.ggPrpult/Cuth>
match.fun("print.ggplot")
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'print.ggplot' of mode 'function' was not found
由于未导出print.ggplot
,match.fun
无法找到它
但是,get
确实找到了它:
get("print.ggplot", envir=environment(ggplot))
function (x, newpage = is.null(vp), vp = NULL, ...)
{
set_last_plot(x)
if (newpage)
grid.newpage()
data <- ggplot_build(x)
gtable <- ggplot_gtable(data)
if (is.null(vp)) {
grid.draw(gtable)
}
else {
if (is.character(vp))
seekViewport(vp)
else pushViewport(vp)
grid.draw(gtable)
upViewport()
}
invisible(data)
}
<environment: namespace:ggplot2>
get(“print.ggplot”,envir=environment(ggplot))
函数(x,newpage=is.null(vp),vp=null,…)
{
设置最后一个绘图(x)
如果(新页)
grid.newpage()
数据+1问得好。您的软件包是在github上还是在我们可以看到代码的地方?您是否也可以添加1)从名称空间文件中提取的显示topicmodels
已导入的内容,以及2)从说明中提取的显示Imports:topicmodels
?您使用的是Imports:topicmodels
还是dependens:top>icmodels
?我正在使用依赖:topicmodels
谢谢,这非常有用。
match.fun("print.ggplot")
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'print.ggplot' of mode 'function' was not found
get("print.ggplot", envir=environment(ggplot))
function (x, newpage = is.null(vp), vp = NULL, ...)
{
set_last_plot(x)
if (newpage)
grid.newpage()
data <- ggplot_build(x)
gtable <- ggplot_gtable(data)
if (is.null(vp)) {
grid.draw(gtable)
}
else {
if (is.character(vp))
seekViewport(vp)
else pushViewport(vp)
grid.draw(gtable)
upViewport()
}
invisible(data)
}
<environment: namespace:ggplot2>