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


当前回答

# remove all objects but selected
rm(list = ls()[which("key_function" != ls())])

其他回答

我刚刚花了几个小时来寻找一个类似但略有不同的问题的答案——我需要能够删除R中的所有对象(包括函数),除了少数向量。

一种方法是:

rm(list=ls()[! ls() %in% c("a","c")])

我想保留的向量命名为a和c。

希望这能帮助寻找同样解决方案的人!

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

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

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

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

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

这个怎么样?

# 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)
}