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


当前回答

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

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

其他回答

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

将v替换为要保留的对象的名称

rm(list=(ls()[ls()!="v"]))

hat-tip: http://r.789695.n4.nabble.com/Removing-objects-and-clearing-memory-tp3445763p3445865.html

require(gdata)
keep(object_1,...,object_n,sure=TRUE)
ls()

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

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

这利用了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"