setMethod and package Matrix

老子叫甜甜 提交于 2019-12-14 02:46:50

问题


I am creating an S4 class that uses package Matrix and then using setMethod to redefine "sin" for my class

> library(Matrix)
> setClass("foo",slots=list(z="Matrix"))
> setMethod("sin",signature(x="foo"),function(x){return(cos(x@z))})
[1] "sin"

however, even before I get started using my class I encounter a problem

> 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

Why does the second use of sin(y) fail ? This is my first attempt at programming with S4 classes. Any help will be much appreciated.


回答1:


At some level this looks like a bug that should be reported to the R-devel mailing list. But sin() is a member of the Math 'group generic' (see ?GroupGenericFunctions), and one could implement

setMethod("Math", "foo", function(x) callGeneric(x@z))



回答2:


Just posted an alternative solution in a thread with a similar question https://stackoverflow.com/a/37566785/2116352 without having to overload the whole generic group. tl;dr: Overload the individual function within a package and load the package.



来源:https://stackoverflow.com/questions/34221612/setmethod-and-package-matrix

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