2

I have an R6 class that I wish to have the %*% method defined. I have seen in another question how to accomplish this with a new S4 method. However, I have tried this approach and it fails when I try to create the S4 %*% method for my R6 class. For example:

library(R6)
setOldClass(c("TestR6", "R6"))
TestR6 <- R6Class("TestR6", public = list(.x = "numeric"))

setMethod("%*%", c(x = "TestR6", y = "TestR6"),
          function(x, y){
            print('the matmult operation')
          }
)

x <- TestR6$new()
y <- TestR6$new()

x %*% y

Error in x %*% y : requires numeric/complex matrix/vector arguments

And yet, it still works if I create the foo method.

setGeneric("foo", signature = "x",
  def = function(x) standardGeneric("foo")
)
setMethod("foo", c(x = "R6"),
  definition = function(x) {
    "I'm the method for `R6`"
  })
try(foo(x = TestR6$new()))
[1] "I'm the method for `R6`"

Why doesn't it work for the %*% method?

cdeterman
  • 19,630
  • 7
  • 76
  • 100
  • The `%*%` doesn't seem to be marked as generic; it's primitive. Interesting. It [seems like it does check for S4 methods](https://github.com/wch/r-source/blob/8e191101cbd945650436bce628bf47cbd550a47e/src/main/array.c#L1215), maybe that's different for R6? – MrFlick Nov 09 '17 at 20:46
  • Look at the output `%*%`. It calls a `.Primitive`, not `UseMethod`. You \*can\* override this directly by assignment, however it's just a bad idea. There was another thread about using `+` for string concatention that you can search for some ideas. – thc Nov 09 '17 at 21:14
  • @thc do you have a link to that thread? – cdeterman Nov 09 '17 at 21:28
  • Here it is: https://stackoverflow.com/questions/4730551/making-a-string-concatenation-operator-in-r – thc Nov 09 '17 at 21:29
  • @MrFlick so does that mean with R6 classes, for primitives like `%*%`, `+`, and `-` I am basically SOL unless I want to 'override' functions? – cdeterman Nov 09 '17 at 21:40

0 Answers0