How can I remove all objects but one from the workspace in R?
I have a workspace with lots of objects and I would like to remove all but one. Ideally I would like to avoid having to type rm(obj.1, obj.2... obj.n)
. Is it possible to indicate remove all objects but these ones
?
Here is a simple construct that will do it, by using setdiff
:
rm(list=setdiff(ls(), "x"))
And a full example. Run this at your own risk - it will remove all variables except x
:
x <- 1
y <- 2
z <- 3
ls()
[1] "x" "y" "z"
rm(list=setdiff(ls(), "x"))
ls()
[1] "x"
Using the keep
function from the gdata
package is quite convenient.
> 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"