In R, how to implement operator overloading (like +, -, *, ./) for a new class? I checked the source code of the zoo library, in ops.R. Does the following code do the job?
Ops.zoo <- function (e1, e2)
{
e <- if (missing(e2)) {
NextMethod(.Generic)
}
else if (any(nchar(.Method) == 0)) {
NextMethod(.Generic)
}
else {
merge(e1, e2, all = FALSE, retclass = NULL)
NextMethod(.Generic)
}
out <- if (is.null(attr(e, "index")))
zoo(e, index(e1), attr(e1, "frequency"))
else
e
# the next statement is a workaround for a bu g in R
structure(out, class = class(out))
}
I am lost on the merge(e1,e2,..) block. I tested it with
e1 <- zoo(rnorm(5), as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-")))
e2 <- e1
test <- merge(e1, e2, all = FALSE, retclass = NULL)
but then test is NULL. How does the e <- {test; NextMethod(.Generic)} work?
I think you may be looking at an example that is more complicated than necessary. It certainly seems worth reading
?Ops(as the commenter above stated), but for basic examples you can do this pretty easily:If something that simple doesn’t suit your needs I would suggest (in addition to
?Ops) looking at a simpler example like(note backward single quotes)