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
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)
)
}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With