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


当前回答

下面的操作将从控制台删除所有对象

rm(list = ls())

其他回答

使用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"

要保存对象列表,可以使用:

rm(list=setdiff(ls(), c("df1", "df2")))

这个怎么样?

# 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"

假设你想从环境中删除除df之外的所有对象:

rm(list = ls(pattern="[^df]"))