R:zoo对象中的运算符重载和Ops.zoo
在 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 <- {测试; NextMethod(.Generic)}
有效吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您可能正在查看一个比必要的更复杂的示例。这当然似乎值得阅读
?Ops
(如上面的评论者所述),但对于基本示例,您可以很容易地做到这一点:如果这么简单的东西不适合您的需求,我会建议(除了
?Ops
) 看一个更简单的例子,例如(注意向后单引号)
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)