Export S3 method for a 'function' class object

时光总嘲笑我的痴心妄想 提交于 2021-01-27 15:15:56

问题


Function objects seems to work well with dispatching of S3 methods.
But for some reason they cannot be exported in NAMESPACE file.

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"

But when I try to define export in NAMESPACE as:

export(as.abc)
S3method(as.abc, list)
S3method(as.abc, function)

It throws an error while R CMD check:

* 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?


回答1:


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:

(Note that function and class names may be quoted, and reserved words and non-standard names such as [<- and function must be.)



来源:https://stackoverflow.com/questions/33844301/export-s3-method-for-a-function-class-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!