我有一个有很多对象的工作空间,我想删除所有的,但只有一个。理想情况下,我希望避免键入rm(obj。1、obj.2……obj.n)。是否有可能指示删除除这些对象之外的所有对象?


当前回答

下面是一个简单的构造,通过使用setdiff来实现:

rm(list=setdiff(ls(), "x"))

这是一个完整的例子。运行此程序的风险由你自己承担——它将删除除x之外的所有变量:

x <- 1
y <- 2
z <- 3
ls()
[1] "x" "y" "z"

rm(list=setdiff(ls(), "x"))

ls()
[1] "x"

其他回答

这个怎么样?

# Removes all objects except the specified & the function itself.

rme <- function(except=NULL){
  except = ifelse(is.character(except), except, deparse(substitute(except)))
  rm(list=setdiff(ls(envir=.GlobalEnv), c(except,"rme")), envir=.GlobalEnv)
}

这利用了ls()的模式选项,在这种情况下,你有很多具有相同模式的对象,而你不想保留:

> foo1 <- "junk"; foo2 <- "rubbish"; foo3 <- "trash"; x <- "gold"  
> ls()
[1] "foo1" "foo2" "foo3" "x"   
> # Let's check first what we want to remove
> ls(pattern = "foo")
[1] "foo1" "foo2" "foo3"
> rm(list = ls(pattern = "foo"))
> ls()
[1] "x"

使用gdata包中的keep函数非常方便。

> ls()
[1] "a" "b" "c"

library(gdata)
> keep(a) #shows you which variables will be removed
[1] "b" "c"
> keep(a, sure = TRUE) # setting sure to TRUE removes variables b and c
> ls()
[1] "a"
require(gdata)
keep(object_1,...,object_n,sure=TRUE)
ls()

从函数内部,rm .GlobalEnv中除函数外的所有对象

initialize <- function(country.name) {

  if (length(setdiff(ls(pos = .GlobalEnv), "initialize")) > 0) {
    rm(list=setdiff(ls(pos = .GlobalEnv), "initialize"), pos = .GlobalEnv)
  }

}