Background
I want to write a package overloading +
, -
, %%
on matrices, to make it easier to use R for the quick matrix calculations one might do in Matlab:
+X
computest(X)
(binaryX+Y
works as normal)-X
computessolve(X)
(binaryX-Y
works as normal)-I(X)
computes-X
X%%Y
computesY%*%X
(write multiplications right-to-left, for reasons beyond scope of question)
Example use of the package:
library(mymatrixpackage)
X <- matrix(1:6, nrow = 3)
y <- matrix(1:3, nrow = 3)
+X == t(X)
X+X == 2*x
# soln to lm coefficients (remember: read right-to-left)
y%%+X%%-(X%%+X) == solve(t(X)%*%X)%*%t(X)%*%y
Main Question
For a matrix X
, how can I make +X
dispatch to +.matrix
(a function I can define). +X
uses the internal method and seems to ignore +.matrix
.
I think I need to use Ops
, or something to do with group generics.
Alternative solution
I have successfully implemented this idea using an s3 class “tmatrix” and:
`+.tmatrix` <- function(X,Y) {
if (missing(Y)) {
t(X)
} else {
structure(unclass(X)+unclass(Y), class = oldClass(X))
}
}
It would be better to not use an s3 class because:
- Need to do:
attr(X, "class") <- "tmatrix"
- many operations (eg
[
) loseX
‘s class attribute, and so I need to overload those operations as well.