How to remove all user methods and classes from the R workspace?

I've been experimenting a lot with S4 classes lately, and it pains me to restart R to clear all class definitions and custom methods from my workspace. Obviously rm(list=ls(all.names=TRUE)) useless. I could manually delete all the classes and methods individually by writing the lines one by one, but I'm sure there will be an easier way.

An example of a demonstration of 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 removing everything with rm() :

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

However, the class definition and user 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 deleted using rm , but the method referencing mySlot() remained. I would like to know how to remove all classes and all user methods in one fell swoop.

+6
source share
2 answers

It's hard to understand that you hope that R will remember your session. You can

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

or if you lost information about what you did, the following hacks may 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) 
+7
source

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

You can remove the class definition with removeClass . But, eliminating the definition of a class, methods that are associated with it are not deleted. To really remove a class, you must remove the class to remove all its methods using removeMethod .

It hurts so much that either restarting R or it’s better to create a custom package where you define your class and use some devtools tools to load everything using something like:

 devtools::load_all(".") 
+1
source

Source: https://habr.com/ru/post/975664/


All Articles