(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 intereste
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 %/%
:
?Ops
as.g5 <- function(x){
if(!inherits(x, "g5")) class(x) <- c("g5", class(x))
x %% 5
}
print.g5 <- function(x, ...){
cat("G5 equivalent:\n")
cat(x %% 5)
invisible(x)
}
If you wanted two operators you might be looking for:
`+.g5` <- function(e1, e2){
NextMethod(e1 ,e2) %% 5
}
`*.g5` <- function(e1, e2){
NextMethod(e1 ,e2) %% 5
}
x <- as.g5(0:10)
y <- as.g5(5)
x + y
#G5 equivalent:
#0 1 2 3 4 0 1 2 3 4 0
y <- as.g5(2)
x * y
#G5 equivalent:
#0 2 4 1 3 0 2 4 1 3 0
It's also possible to use these operation on "volatile" versions of vectors:
as.g5(1:10) * as.g5(1:10)
# G5 equivalent:
# 1 4 4 1 0 1 4 4 1 0