dudu
dudu

Reputation: 705

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)

Upvotes: 4

Views: 395

Answers (1)

jamieRowen
jamieRowen

Reputation: 1549

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.

Upvotes: 5

Related Questions