R中的运算符重载和类定义:使用其他基础字段/语料库 [英] Operator overloading and class definition in R: Use a different base field/corpus
问题描述
((我在数学意义上使用了字段"一词 ; R
已经使用的基本字段/语料库包括实数和复数.)
(I'm using the word "field" in the mathematical sense; base fields/corpora which R
already uses include the real and complex numbers.)
我有兴趣允许其他一些基本字段/语料库(例如F₅,它是基数5中的模块化算术).为此,我需要
I'm interested in allowing some other base fields/corpora (like F₅, which is modular arithmetic in base 5). To do that I would need to
- 定义新的数据类型
- 重载相关运算符(
+
,*
,也许还有更多) - 也许还有别的吗?例如,是否与其他功能集成?
- define a new data type
- overload the relevant operators (
+
,*
, and maybe more) - maybe something else? e.g., integrate with other functionality?
那么,如何在R
中定义新的数据类型或重载运算符?
So, how does one define a new data type or overload operators in R
?
推荐答案
我发现Hadley Wickham的 devtools Wiki 是宝贵的资源R中的类入门.特别是,请阅读以下部分:
I found Hadley Wickham's devtools wiki an invaluable resource for getting started with classes in R. In particular, read the sections on:
- S3 classes
- S4 classes
此处是说明S3
类中某些概念的起点.让我们将您的新类称为f5
.至少,您可能希望创建以下方法:
Here is a starting point that illustrates some of the concepts in S3
classes. Let's call your new class f5
. At a minimum, you would probably want to create methods for:
- 强制:
as.f5
- 测试:
is.f5
- 一些基本运算符:
+.f5
- 处理打印的类:
print.f5
- Coercion:
as.f5
- Test:
is.f5
- Some basic operators:
+.f5
- A class to handle printing:
print.f5
某些代码(使用包GLDEX
中的digitsBase
进行基本转换):
Some code (using digitsBase
in package GLDEX
to do the base conversion):
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
这篇关于R中的运算符重载和类定义:使用其他基础字段/语料库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!