导出“功能"类对象的S3方法 [英] Export S3 method for a 'function' class object
问题描述
函数对象似乎可以很好地与S3方法的调度配合使用.
但是由于某些原因,它们无法导出到NAMESPACE文件中.
Function objects seems to work well with dispatching of S3 methods.
But for some reason they cannot be exported in NAMESPACE file.
以下代码可用于分派给 *.function
方法:
Below code works with dispatching to *.function
method:
as.abc = function(x, ...){
UseMethod("as.abc")
}
as.abc.list = function(x, ...){
stopifnot(is.list(x))
structure(x, class="abc")
}
as.abc.function = function(x, ...){
stopifnot(is.function(x))
structure(x, class="abc")
}
# list
l = as.abc(list(1))
str(l)
#List of 1
# $ : num 1
# - attr(*, "class")= chr "abc"
# function
f = as.abc(function(x) x)
str(f)
#function (x)
# - attr(*, "srcref")=Class 'srcref' atomic [1:8] 1 12 1 24 12 24 1 1
# .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x3dbb848>
# - attr(*, "class")= chr "abc"
但是当我尝试在NAMESPACE中将导出定义为:
But when I try to define export in NAMESPACE as:
export(as.abc)
S3method(as.abc, list)
S3method(as.abc, function)
在 R CMD检查时抛出错误:
* checking package namespace information ... ERROR
Invalid NAMESPACE file, parsing gives:
Error in parse(nsFile, keep.source = FALSE, srcfile = NULL): 29:26: unexpected ')'
28: S3method(as.abc, list)
29: S3method(as.abc, function)
我也尝试将其包装到`
中,但这也无济于事
I tried also wrap into `
but it didn't help too
S3method(as.abc, `function`)
为函数类导出方法的正确方法是什么?
What is the proper way to export method for a function class?
推荐答案
根据编写R扩展部分1.a,注册用于类函数对象的S3方法时,必须使用常规引号:
According to Writing R Extensions section 1.5.2, you have to use regular quotes when registering S3 methods that work on objects of class function:
(请注意,函数和类的名称可以用引号引起来,保留字和非标准名称(例如[<-和function必须使用.)
(Note that function and class names may be quoted, and reserved words and non-standard names such as [<- and function must be.)
这篇关于导出“功能"类对象的S3方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!