R 中的运算符重载和类定义:使用不同的基本字段/语料库
(我使用“字段”这个词数学意义上的;基本字段R
已经使用的 /corpora 包括实数和复数。)
我有兴趣允许一些其他基本字段/语料库(例如 F₅,它是基本的模块化算术) 5)。为此,我需要
- 定义一个新的数据类型,
- 重载相关运算符(
+
、*
,也许还有更多), - 也许还有其他操作?例如,与其他功能集成?
那么,如何在 R 中定义新的数据类型或重载运算符呢?
(I'm using the word "field" in the mathematical sense; base fields/corpora which R
already uses include the real and complex numbers.)
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?
So, how does one define a new data type or overload operators in R
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我对你的问题的解释与@Andrie有点不同,但他已经完成了一堆所需的S3类工作。我以为您想在具有五个元素或可能是一个环的群上开发群运算。然后,您可能需要一个带有单位元素 == 0 的“+”操作,也许需要一个带有单位元素 == 1 的“*”操作。
如果您希望将非负整数映射到此,您可以使用模算术运算符 < code>%% 或许还有
%/%
:如果您想要两个运算符,您可能正在寻找:
也可以在向量的“易失性”版本上使用这些操作:
I interpreted your question a bit differently than @Andrie, but he has already done a bunch of the needed S3 class work. I thought you wanted to develop group operations on a group with five elements, or perhaps a ring. You would then want a "+" operation with an identity element == 0 and perhaps a "*" operation with an identity element == 1.
If you wanted the nonnegative integers mapped into this, you would use the modulo arithmetic operators,
%%
and perhaps%/%
:If you wanted two operators you might be looking for:
It's also possible to use these operation on "volatile" versions of vectors:
我发现 Hadley Wickham 的 devtools wiki 是开始使用 R 类的宝贵资源。特别是,请阅读以下部分:
这是一个开始说明
S3
类中的一些概念的点。我们将新类命名为f5
。至少,您可能希望为以下内容创建方法:as.f5
is.f5
+.f5
>print.f5
一些代码(使用
GLDEX
包中的digitsBase
进行基数转换):I found Hadley Wickham's devtools wiki an invaluable resource for getting started with classes in R. In particular, read the sections on:
Here is a starting point that illustrates some of the concepts in
S3
classes. Let's call your new classf5
. At a minimum, you would probably want to create methods for:as.f5
is.f5
+.f5
print.f5
Some code (using
digitsBase
in packageGLDEX
to do the base conversion):