
Untitled
By: a guest on
May 24th, 2012 | syntax:
None | size: 1.11 KB | hits: 14 | expires: Never
Operator overloading and class definition in R: Use a different base field/corpus
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
?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)
}
`+.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
as.g5(1:10) * as.g5(1:10)
# G5 equivalent:
# 1 4 4 1 0 1 4 4 1 0