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.
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.
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
or this works for multiple objects even though it returns an error message
if you only have a few objects in the workspace you could count and use their numeric index
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.
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 exampleEven 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
andobj2