R:zoo对象中的运算符重载和Ops.zoo

发布于 2024-11-10 08:37:38 字数 973 浏览 2 评论 0原文

在 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)

,但是 testNULLe <- {测试; 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小忆控 2024-11-17 08:37:39

我认为您可能正在查看一个比必要的更复杂的示例。这当然似乎值得阅读 ?Ops (如上面的评论者所述),但对于基本示例,您可以很容易地做到这一点:

> `+.mychar` <- function(e1,e2) paste(e1,e2)
> x <- "a"
> y <- "b"
> class(x) <- "mychar"
> x+y
[1] "a b"

如果这么简单的东西不适合您的需求,我会建议(除了?Ops) 看一个更简单的例子,例如

`+.Date`

(注意向后单引号)

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:

> `+.mychar` <- function(e1,e2) paste(e1,e2)
> x <- "a"
> y <- "b"
> class(x) <- "mychar"
> x+y
[1] "a b"

If something that simple doesn't suit your needs I would suggest (in addition to ?Ops) looking at a simpler example like

`+.Date`

(note backward single quotes)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文