6

Let's say I have an S4 class called testClass. The contents are irrelevant the purpose of this question but let's make it contain a numeric value.

#' An S4 class that stores a list.
#' @export
setClass("testClass", 
                 representation(a="numeric"))

I would like to define a method that works like the taking the opposite of an object. For example:

vec <- rnorm(10)
-vec

I thought this would be declaring an Arith method with the first argument missing.

#' @export
setMethod("Arith", c(e1="missing", e2="testClass"),
                    function(e1, e2)
                    {
                        op = .Generic[[1]]
                        switch(op,
                            `-` = return(-e2@a)
                        )
                    }
)

However, when I try to apply the method I get the following error:

tc <- new("testClass", a=2)
-tc

Error in -tc : invalid argument to unary operator

cdeterman
  • 19,630
  • 7
  • 76
  • 100

1 Answers1

7

Hah! After fiddling some more with it I discovered that it is the e2 argument that needs to be missing. The following works:

#' @export
setMethod("Arith", c(e1="testClass", e2="missing"),
                    function(e1, e2)
                    {
                        op = .Generic[[1]]
                        switch(op,
                            `-` = return(-e1@a)
                        )
                    }
)
cdeterman
  • 19,630
  • 7
  • 76
  • 100
  • Nice demo. Just out of curiosity, where does that `.Generic` come from (i.e. where is its value to be found)? – Josh O'Brien Dec 10 '15 at 18:18
  • ` ?.Generic` produces after some scrolling: `‘.Generic’ is a length-one character vector naming the generic function.` – thothal Dec 10 '15 at 18:26
  • Is there any difference if you try `setMethod("-", c(e1="testClass", e2="missing"), function(e1, e2) -e1@a)`? – nicola Dec 10 '15 at 20:08