R S4类和Matrix包中的重载+运算符 [英] Overloading + operator in R S4 classes and Matrix package

查看:198
本文介绍了R S4类和Matrix包中的重载+运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试重载+运算符并将Matrix包与稀疏矩阵一起使用时,我得到一个怪异的效果.我首先定义一个非常简单的类,该类不使用Matrix包,但具有+运算符.然后,我对两个稀疏矩阵求和.第一个M+M加法提供了预期的结果,但第二个抛出错误.这是生成错误的非常简单的代码:

I get a weird effect when trying to overload the + operator and using the Matrix package with sparse matrices. I first define a very simple class that does not use the Matrix package but has a + operator. I then sum two sparse matrices. The first M+M addition delivers the expected result but the second throws an error. Here is a very simple code that generates the error:

require(Matrix)
setClass("TestM",representation(M='numeric'))
setMethod("initialize", "TestM", function(.Object,x) { 
  .Object@M = x
  .Object
})
setMethod("+", c("TestM","TestM"), function(e1,e2) {
  e1@M + e2@M
})

M = Matrix(diag(1:10),sparse=T)
M+M  # > FINE
M+M  # > ERROR

M = Matrix(diag(1:10),sparse=F)
M+M  # > FINE
M+M  # > FINE

第二次添加会引发以下错误:

The second addition throws the following error:

Error in forceSymmetric(callGeneric(as(e1, "dgCMatrix"), as(e2, "dgCMatrix"))) : 
  error in evaluating the argument 'x' in selecting a method for function
'forceSymmetric': Error in .Arith.Csparse(e1, e2, .Generic, class. = "dgCMatrix") :
  object '.Generic' not found

如果矩阵不稀疏,则不会发生错误.我定义的+和sparseMatrix的+之间是否存在一些干扰?我不能正确定义+运算符吗?

And the error does not happen if the matrices are not sparse. Is there some interference between the + I define and the + for sparseMatrix ? Do I not define the + operator correctly?

谢谢!

推荐答案

尝试将Ops类设置为重载:

Try setting the Ops class to be overloaded:

> setMethod(Ops, c("TestM","TestM"), function(e1,e2) {
+   e1@M + e2@M
+ })
[1] "Ops"
attr(,"package")
[1] "base"
> 
> M = Matrix(diag(1:10),sparse=T)
> M+M  # > FINE
10 x 10 sparse Matrix of class "dsCMatrix"

 [1,] 2 . . .  .  .  .  .  .  .
 [2,] . 4 . .  .  .  .  .  .  .
 [3,] . . 6 .  .  .  .  .  .  .
 [4,] . . . 8  .  .  .  .  .  .
 [5,] . . . . 10  .  .  .  .  .
 [6,] . . . .  . 12  .  .  .  .
 [7,] . . . .  .  . 14  .  .  .
 [8,] . . . .  .  .  . 16  .  .
 [9,] . . . .  .  .  .  . 18  .
[10,] . . . .  .  .  .  .  . 20
> M+M  # (NOT error)... was  ERROR
10 x 10 sparse Matrix of class "dsCMatrix"

 [1,] 2 . . .  .  .  .  .  .  .
 [2,] . 4 . .  .  .  .  .  .  .
 [3,] . . 6 .  .  .  .  .  .  .
 [4,] . . . 8  .  .  .  .  .  .
 [5,] . . . . 10  .  .  .  .  .
 [6,] . . . .  . 12  .  .  .  .
 [7,] . . . .  .  . 14  .  .  .
 [8,] . . . .  .  .  . 16  .  .
 [9,] . . . .  .  .  .  . 18  .
[10,] . . . .  .  .  .  .  . 20

这篇关于R S4类和Matrix包中的重载+运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆