在R中,如何为新类实现操作符重载(如+、-、*、./)?我在ops.R中查看了zoo库的源代码。下面的代码可以完成这项工作吗?
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)}是如何工作的?
发布于 2011-05-31 03:58:32
我认为您可能正在查看一个比必要的更复杂的示例。它看起来确实值得阅读?Ops (正如上面的评论者所说的),但是对于基本的例子,你可以很容易地做到这一点:
> `+.mychar` <- function(e1,e2) paste(e1,e2)
> x <- "a"
> y <- "b"
> class(x) <- "mychar"
> x+y
[1] "a b"如果这么简单的东西不能满足您的需求,我建议(除了?Ops之外)看一个更简单的例子,比如
`+.Date`(注意后面的单引号)
https://stackoverflow.com/questions/6177640
复制相似问题