在 R 中,如何为新类实现运算符重载(如+
, -
, *
, ./
)?我检查了动物园库的源代码,在ops.R
. 以下代码可以完成这项工作吗?
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))
}
我迷路了merge(e1,e2,..)
。我用它测试过
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)
但然后test
是NULL
。工作如何e <- {test; NextMethod(.Generic)}
?