我正在创建一个使用包Matrix的S4类,然后使用setMethod为我的类重新定义“sin”
> library(Matrix)
> setClass("foo",slots=list(z="Matrix"))
> setMethod("sin",signature(x="foo"),function(x){return(cos(x@z))})
[1] "sin"
然而,甚至在我开始使用我的类之前,我遇到了一个问题
> y<-Matrix(c(1,2,1,2),2,2)
> sin(y)
2 x 2 Matrix of class "dgeMatrix"
[,1] [,2]
[1,] 0.8414710 0.8414710
[2,] 0.9092974 0.9092974
> sin(y)
Error in match(x, table, nomatch = 0L) : object '.Generic' not found
为什么sin(y)的第二次使用会失败?这是我第一次尝试使用S4类进行编程。任何帮助都将不胜感激。
在某种程度上,这看起来像是一个应该报告给R-devel邮件列表的bug。但是sin()
是Math
“组泛型”的成员(参见?GroupGenericFunctions
),并且可以实现
setMethod("Math", "foo", function(x) callGeneric(x@z))
刚刚在一个线程中发布了一个类似问题的替代解决方案https://stackoverflow.com/a/37566785/2116352而不必重载整个通用组。tl; dr:重载包中的单个函数并加载包。