如何从R工作区中删除所有自定义方法和类?

Wil*_*son 6 r class s4

我最近一直在尝试使用S4类,并且重新启动R以清除工作区中的所有类定义和自定义方法是一件痛苦的事.显然rm(list=ls(all.names=TRUE))是没用的.我可以通过逐行编写行来单独手动删除所有类和方法,但我确信必须有一个更简单的方法.

一个展示我的问题的例子:

.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])
})
Run Code Online (Sandbox Code Playgroud)

尝试删除所有内容rm():

rm(list=ls(all.names=TRUE))
Run Code Online (Sandbox Code Playgroud)

但是,类定义和自定义方法仍然存在:

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

因为mySlot()它是一个被删除的对象rm,但方法引用mySlot()仍然存在.我想知道如何一举删除所有类和所有自定义方法.

Mar*_*gan 7

很难知道你希望R会记住你的会话.您可以

removeClass("myClass", where=.GlobalEnv)
removeMethods("[", where=.GlobalEnv)
Run Code Online (Sandbox Code Playgroud)

或者,如果你已经忘记了所做的一切,那么下面的黑客可能会有所帮助

## 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)
Run Code Online (Sandbox Code Playgroud)