Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define S4 method for taking the opposite of the object?

Tags:

r

s4

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

like image 547
cdeterman Avatar asked Dec 10 '15 17:12

cdeterman


1 Answers

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)
                        )
                    }
)
like image 121
cdeterman Avatar answered Sep 29 '22 12:09

cdeterman