How can I remove all objects but one from the workspace in R?
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"
I think another option is to open workspace in RStudio and then change list to grid at the top right of the environment(image below). Then tick the objects you want to clear and finally click on clear.
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"