## #define a class ##use Splus6 setClass("point", representation(x="numeric", y="numeric")) pt1 <- new("point", x=1,y=3) pt1@x pt1@y class(pt1) setClass("otherpt", representation(r="numeric", theta="numeric")) pt2 <- new("otherpt", r=4,theta=pi/4) pt2@r pt2@theta class(pt2) ## access via methods setGeneric("Xpos", function(obj) standardGeneric("Xpos")) setMethod("Xpos", signature(obj="point"), function(obj) obj@x) setGeneric("Ypos", function(obj) standardGeneric("Ypos")) setMethod("Ypos", signature(obj="point"), function(obj) obj@y) ## Xpos(pt1) Ypos(pt1) ##methods for the r-theta class setMethod("Xpos", signature(obj="otherpt"), function(obj) obj@r*cos(obj@theta)) setMethod("Ypos", signature(obj="otherpt"), function(obj) obj@r*sin(obj@theta)) Xpos(pt2) Ypos(pt2) ##what have we gained at this point? ##we just call Xpos -- we don't need to call anything else ##the generic function handles the dispatching ##printing: ##use cat etc to customize the display of your objects setMethod("show", signature("otherpt"), function(object) print("Hiya")) pt2 removeMethod("show", signature("otherpt")) pt2 ##plotting ##we could make this a ##for now we ignore user supplied col, xlim and ylim values ##'cause we like our own better ;-) plotxy <- function(x, col, xlim, ylim, ...) { xval <- Xpos(x) yval <- Ypos(x) plot(xval,yval, xlim=c(0,xval+1), ylim=c(0,yval+1), ...) } plotxy(pt2)