[R] setting different environments

Assa Yeroslaviz
Thu, 07 Jan 2010 09:55:23 -0000

Hallo,

I have a set of S4 and S3 classes together in one script.
While running this script I create a lot of new functions and objects
An example for S3 and S4 classes:
## S3 classes
pt <- list(x=1,y=2)
class(pt) <- "xypoint"
xpos <- function(x, ...) UseMethod("xpos")
xpos.xypoint <- function(x) x$x
ypos <- function(x, ...) UseMethod("ypos")
ypos.xypoint <- function(x) x$y

print.xypoint <- function(x) {
  cat("xypoint\n")
  cat("x: ", xpos(x), " y: ", ypos(x), "\n")
}
#####################################################
## S4 classes
setClass("point", representation(x="numeric",
y="numeric"))

## Objekt
new("point", x=3, y=4)
# new("point", x=17, y=5)

## Generics
setGeneric("xcoord", function(object)
standardGeneric("xcoord"))
setGeneric("ycoord", function(object)
standardGeneric("ycoord"))
setGeneric("showpoint", function(object)
standardGeneric("showpoint"))

setMethod("xcoord", "point", function(object) object@x)
setMethod("ycoord", "point", function(object) object@y)

setMethod("showpoint", "point", function(object) {
  cat("x=", xcoord(object), ", y=", ycoord(object),
"\n")
})
setMethod("show", "point", function(object) {
  showpoint(object)
})

setMethod("+", c("point","point"), function(e1,e2)
{
  newx <- xcoord(e1) + xcoord(e2)
  newy <- ycoord(e1) + ycoord(e2)
  return(new("point", x=newx, y=newy))
})

setMethod("-", c("point", "point"), function(e1,
e2) {
  newx <- xcoord(e1) - xcoord(e2)
  newy <- ycoord(e1) - ycoord(e2)
  return(new("point", x=newx, y=newy))
})

setGeneric("point", function(p) standardGeneric("point"))
setMethod(f="point", signature="point",
definition=function(p) {
points(xcoord(p), ycoord(p))})

This two classes creates various functions and objects. This are being saved
under ".GlobalEnv".

My Problem is, that I have a lot of this kind of classes.

I would like to know whether or not there is a possibility to put these
functions and objects in a different environemnt, so that they won'e be
saved under my working directory.

Can I save each class in a different environment?

How, if possible can I than access this functions?

Thanks in advance

Assa

	[[alternative HTML version deleted]]