iso*_*mes 1 oop math r operator-overloading abstract-algebra
(我在数学意义上使用"字段"一词; R已经使用的基本字段/语料库包括实数和复数.)
我有兴趣允许其他一些基本字段/语料库(如F 5,它是基础5中的模运算).要做到这一点,我需要
+,*或许更多)那么,如何定义新的数据类型或重载运算符R呢?
我发现Hadley Wickham的devtools wiki是开始使用R中的类的宝贵资源.特别是,请阅读以下部分:
这是一个起点,说明了S3类中的一些概念.我们打电话给你的新班级f5.至少,您可能希望为以下方法创建方法:
as.f5is.f5+.f5print.f5一些代码(digitsBase在包中使用进行GLDEX基本转换):
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
Run Code Online (Sandbox Code Playgroud)