Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 24th, 2012  |  syntax: None  |  size: 1.11 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Operator overloading and class definition in R: Use a different base field/corpus
  2. library(GLDEX)
  3.  
  4. as.f5 <- function(x){
  5.   if(!inherits(x, "f5")) class(x) <- c("f5", class(x))
  6.   x
  7. }
  8.  
  9. is.f5 <- function(x){
  10.   inherits(x, "f5")
  11. }
  12.  
  13. `+.f5` <- function(e1, e2){
  14.   NextMethod(e1, e2)
  15. }
  16.  
  17. print.f5 <- function(x, ...){
  18.   # Next line from ?GLDEX::digitsBase
  19.   b2ch <- function(db) noquote(gsub("^0+(.{1,})$"," 1",
  20.                            apply(db, 2, paste, collapse = "")))
  21.  
  22.   cat("Base 5:n")
  23.   cat(b2ch(digitsBase(x, 5)))
  24.   invisible(x)
  25. }
  26.  
  27.  
  28. x <- as.f5(0:10)
  29. y <- as.f5(5)
  30.  
  31. x + y
  32.  
  33. Base 5:
  34. 10 11 12 13 14 20 21 22 23 24 30
  35.        
  36. ?Ops
  37. as.g5 <- function(x){
  38.   if(!inherits(x, "g5")) class(x) <- c("g5", class(x))
  39.   x %% 5
  40. }
  41.  
  42. print.g5 <- function(x, ...){
  43.  
  44.   cat("G5 equivalent:n")
  45.   cat(x %% 5)
  46.   invisible(x)
  47. }
  48.        
  49. `+.g5` <- function(e1, e2){
  50.    NextMethod(e1 ,e2) %% 5
  51.  }
  52.  
  53.  `*.g5` <- function(e1, e2){
  54.    NextMethod(e1 ,e2) %% 5
  55.  }
  56.  x <- as.g5(0:10)
  57.  y <- as.g5(5)
  58.  
  59.  x + y
  60. #G5 equivalent:
  61. #0 1 2 3 4 0 1 2 3 4 0
  62.  y <- as.g5(2)
  63.  x * y
  64. #G5 equivalent:
  65. #0 2 4 1 3 0 2 4 1 3 0
  66.        
  67. as.g5(1:10) * as.g5(1:10)
  68. # G5 equivalent:
  69. # 1 4 4 1 0 1 4 4 1 0