8

I've been experimenting a lot with S4 classes lately, and it is a pain to restart R in order to clear all class definitions and custom methods from my workspace. Obviously rm(list=ls(all.names=TRUE)) is of no use. I could manually remove all classes and methods individually by writing lines one-by-one, but I'm sure there's got to be an easier way.

An example showcasing my problem:

.myClass <- setClass("myClass", representation=representation(mySlot="numeric"))
mySlot <- function(x) x@mySlot
setMethod("[", signature=c("myClass", "numeric", "missing"), function(x, i, j, ...) {
  initialize(x, mySlot=mySlot(x)[i])
})

Try to remove everything with rm():

rm(list=ls(all.names=TRUE))

However, the class definition and custom method are still present:

> x <- new("myClass", mySlot=1:4)
> x[1]
Error in x[1] : could not find function "mySlot"

Since mySlot() was an object it was removed with rm, but the method referencing mySlot() remained. I'd like to know how to remove all classes and all custom methods in one fell swoop.

Will Beason
  • 3,417
  • 2
  • 28
  • 46
  • 1
    Classes can be removed, AFAIK, with removeClass(). However, I do not know a good way to automate it in your case. If you had a list of class names you could iterate through it and remove the classes with removeClass() though. – ddiez Sep 22 '14 at 16:50

2 Answers2

7

It's hard to know what you're hoping R will remember of your session. You can

removeClass("myClass", where=.GlobalEnv)
removeMethods("[", where=.GlobalEnv)

or if you've lost track of what-all you've done the following hacks might help

## Class definitions are prefixed by '.__C__'
mangled <- grep(".__C__", ls(all=TRUE, envir=.GlobalEnv), value=TRUE)
classes <- sub(".__C__", "", mangled)
for (cl in classes) removeClass(cl, where=.GlobalEnv)

## Methods tables are prefixed by '.__T__'
mangled <- grep(".__T__", ls(all=TRUE, envir=.GlobalEnv), value=TRUE)
methods <- unique(sub(".__T__(.*):.*", "\\1", mangled))
for (meth in methods) removeMethods(meth, where=.GlobalEnv)
Martin Morgan
  • 45,935
  • 7
  • 84
  • 112
  • That does what I need it to do. Thanks! Basically, I wanted R to remember nothing from the session and be able to begin anew. – Will Beason Sep 22 '14 at 17:22
0

This is a comment but it is too long so I put it as an answer.

You can remove the definition of a class using removeClass. But, removing the definition of a class does not remove the methods which are associated to it. To really remove a class, it is necessary to remove the class then to remove all its methods using removeMethod.

This is painful so either you restart R or better is to create a custom package where you define your class and use some tools devtools to load everything use something like:

devtools::load_all(".")
agstudy
  • 119,832
  • 17
  • 199
  • 261