gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 07:10:38 26 4
gpt4 key购买 nike

在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 <- {test; NextMethod(.Generic)}如何工作?

最佳答案

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

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

如果简单的事情不满足您的需求,我建议(除了 ?Ops)看一个更简单的示例,例如
`+.Date`

(请注意向后单引号)

关于r - R:运算符重载和Zoo对象中的Ops.zoo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6177640/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com