rm( ) everything except specific object

大憨熊 提交于 2019-12-24 00:57:24

问题


Does someone have an idea about how can I remove everything in R except one object? Normally, to remove everything I code:

rm(list=ls())

So I tried:

rm(c(list=ls()-my_object))

but it didn’t work.


回答1:


The setdiff() function shows the difference between sets, so we can use this to give the difference between all the objects (ls()), and the object you want to keep. For example

## create some objects
df <- data.frame()
v <- as.numeric()

# show everything in environment
objects()
# [1] "df" "v"

## or similarly
ls()
# [1] "df" "v"

## the setdiff() funciton shows the difference between two sets
setdiff(ls(), "df")
# [1] "v"

# so we can use this to remove everything except 'df'
rm(list = setdiff(ls(), "df"))
objects()
# [1] "df"



回答2:


Even though it was asked a long ago. My answer may help others in future, Suppose you want to remove everything from your environment except obj1 and obj2

x<- which(ls()=="obj1"|ls()=="obj2")
ls1<- ls()[-x]
rm(list = ls1)



回答3:


The way I do it, is pretty much identical to everyone else, but I tend to gravitate towards logical indices usually...

for a single object, using a logical index

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

or this works for multiple objects even though it returns an error message

rm(list=ls()[ls()!= c("object_I_want1", "object_I_want2")])

if you only have a few objects in the workspace you could count and use their numeric index

ls();
#returns all objects in alphabetical order
# [1] "object_I_dont_want"  "object_I_want"  "object_I_dont_want"
rm(list=ls()[-2])

You don't technically need to use ls(). If for any reason you need to keep a running tally of the objects you want to keep, or you already have a set of objects you want to keep or get rid of, or whatever, you could just use an exclusive list sort of like this *although technically it will also leave the object used as the subseting index as well.

exsubset = ls()[ls()!= c("object.I.want1", "object_I_want2")];
rm(list=exsubset)


来源:https://stackoverflow.com/questions/40622964/rm-everything-except-specific-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!