(我使用“字段”这个词 in the mathematical sense ;R
已经使用的基本字段/语料库包括实数和复数。)
我有兴趣允许一些其他基域/语料库(例如 F₅,它是基数 5 中的模块化算法)。为此,我需要
+
、*
,也许更多)那么,如何在 R
中定义新的数据类型或重载运算符?
最佳答案
我找到了 Hadley Wickham 的 devtools wiki开始使用 R 中的类的宝贵资源。特别是,请阅读以下部分:
这里是一个起点,说明了 S3
类中的一些概念。让我们将您的新类命名为 f5
。至少,您可能希望为以下方面创建方法:
as.f5
is.f5
+.f5
print.f5
部分代码(使用 GLDEX
包中的 digitsBase
进行基数转换):
library(GLDEX)
as.f5 <- function(x){
if(!inherits(x, "f5")) class(x) <- c("f5", class(x))
x
}
is.f5 <- function(x){
inherits(x, "f5")
}
`+.f5` <- function(e1, e2){
NextMethod(e1, e2)
}
print.f5 <- function(x, ...){
# Next line from ?GLDEX::digitsBase
b2ch <- function(db) noquote(gsub("^0+(.{1,})$"," \1",
apply(db, 2, paste, collapse = "")))
cat("Base 5:\n")
cat(b2ch(digitsBase(x, 5)))
invisible(x)
}
x <- as.f5(0:10)
y <- as.f5(5)
x + y
Base 5:
10 11 12 13 14 20 21 22 23 24 30
关于oop - R : Use a different base field/corpus 中的运算符重载和类定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8022979/