How to determine the S4 method for accepting the opposite object?

Let's say I have an S4 class called testClass . The content does not matter for this question, but let it contain a numerical value.

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

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

 vec <- rnorm(10) -vec 

I thought this would declare an Arith method with no first argument.

 #' @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 for unary operator

+5
source share
1 answer

Huh! Having caught a few more with him, I discovered that this is an e2 argument, which should be absent. The following works:

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

Source: https://habr.com/ru/post/1237869/


All Articles