Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload matrix multiplication for S3 class in R

How to I overload the matrix multiplication operator in R? I have been able to do it with most other operators (using Ops), but with matrix operations I get this error:

requires numeric/complex matrix/vector arguments

Here is a minimum working example:

speed = function(x){
    structure(list(y = x),
              class = "speed")
}

m = matrix(c(1,2,3,4), ncol = 2)
s = speed(m)

# Addition works fine
`+.speed` = function(e1, e2){ e1$y + e2 }

s + 10

# But matrix multiplication doesn't
`%*%.speed` = function(e1, e2){ e1$y %*% e2 }

s %*% c(1,2)
like image 341
dudu Avatar asked Oct 15 '25 02:10

dudu


1 Answers

I think this is because the %*% is not an S3 generic function by default. You can get around this by making this so.

`%*%.default` = .Primitive("%*%") # assign default as current definition
`%*%` = function(x,...){ #make S3
  UseMethod("%*%",x)
}
`%*%.speed` = function(e1, e2){ e1$y %*% e2 } # define for speed

s %*% c(1,2)
     [,1]
[1,]    7
[2,]   10

You could view Hadley's book if you wanted additional info on this here

Edited in light of comment below.

like image 148
jamieRowen Avatar answered Oct 17 '25 16:10

jamieRowen