Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove all custom methods and classes from an R workspace?

Tags:

class

r

s4

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.

like image 524
Will Beason Avatar asked Sep 22 '14 16:09

Will Beason


1 Answers

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)
like image 79
Martin Morgan Avatar answered Nov 08 '22 00:11

Martin Morgan