我目前正在为S4类编写一个方法,我希望像调用函数一样调用该方法,并使用match.call()。
下面是我所做的最简单的例子:
setClass(
Class = "AClass",
representation = representation(
name = "character"
)
)
setGeneric("meth1", function(object, ...) {
standardGeneric("meth1")
})
setMethod(
f = "meth1",
signature = "AClass",
definition = function(object, method, ..., warnings = TRUE) {
# ...
print(match.call())
return(NA)
})根据这一定义,我看到:
> meth1(new("AClass"), method = "MClust")
.local(object = object, method = "MClust")
[1] NA
> meth1(new("AClass"), method = Mclust)
.local(object = object, method = ..1)
[1] NA问题如下:
match.call()获得的该参数的内容是..1 insetad fo "Mclust"match.call()获得的‘函数的名称’是.local而不是meth1"Mclust"中获得method?发布于 2015-01-13 16:13:58
当涉及到match.call和多层函数调用时,...的工作方式存在一些问题。这与match.call在词法堆栈中搜索以找到要替换的...有关,而不是动态堆栈。我写了一个包试图纠正这些问题:
devtools::install_github("brodieg/matchcall") # <-- the package in question
library(matchcall)
setMethod(
f = "meth1",
signature = "AClass",
definition = function(object, method, ..., warnings = TRUE) {
# ...
print(match.call())
print(match_call())
print(match_call(2))
return(NA)
})
meth1(new("AClass"), method = Mclust)生产:
.local(object = object, method = ..1) # match.call
.local(object = object, method = Mclust) # match_call(), my package
meth1(object = new("AClass"), method = Mclust) # match_call(2), my package offset
[1] NA因此,要回答问题2,获得.local的原因是,有一系列调用最终导致您定义的函数的计算,而S4将该函数存储为.local。
问题1的答案很复杂,但您可以查看我的包中包含的格列奈特中的细节。注意,在C代码中,...参数在内部有名称..1、..2等(来自..1的)
回想一下,函数的计算框架最初包含匹配调用中的name=value对,因此对于.也是。价值..。是一个(特殊)配对列表,其元素由特殊符号..1、..2、…引用。设置了DDVAL位:当遇到其中一个比特时,就会在.评估框架中的符号。
I‘问题3,我不明白。您想要将一个未引用的变量作为参数“方法”,然后将其解释为一个字符吗?
注意,包目前只在github上,但是您可以使用sys.calls来满足您的需要。例如,如果我们在您的方法中运行print(sys.calls()),就会得到:
[[1]]
meth1(new("AClass"), method = Mclust)
[[2]]
meth1(new("AClass"), method = Mclust)
[[3]]
.local(object, ...)您可以直接使用它,但是只有在调用中完全指定参数名称(也就是说,如果有人执行meth1(x, "blah"),则不会在sys.calls中获得它的method=部分),这才能很好地工作。如果您有多个参数或部分指定的参数(例如meth=X),那么您必须做更多的工作来匹配内容(这正是match_call所做的)。
https://stackoverflow.com/questions/27926194
复制相似问题