Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove all objects but one from the workspace in R?

Tags:

r

People also ask

How do I remove all but one object in R?

(ls() %in% c('keepThis','andThis'))] will give the elements excluding 'keepThis' and 'andThis'. Thus rm(list= ls()[! (ls() %in% c('keepThis','andThis'))]) will remove everything except these two objects, and hidden objects. It you want to remove the hidden objects as be use ls(all=TRUE).

How do I remove an object from a workspace in R?

Actually, there are two different functions that can be used for clearing specific data objects from the R workspace: rm() and remove(). However, these two functions are exactly the same. You can use the function you prefer. The previous R code also clears the data object x from the R workspace.

How do I remove all objects in RStudio?

You can do both by restarting your R session in RStudio with the keyboard shortcut Ctrl+Shift+F10 which will totally clear your global environment of both objects and loaded packages.

How do I remove multiple objects from the environment in R?

Use the rm() Function to Remove User-Defined Objects From the Workspace in R. In our R script, we can use the rm() or remove() functions to remove objects. Both functions are identical.


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"

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.

enter image description here


I just spent several hours hunting for the answer to a similar but slightly different question - I needed to be able to delete all objects in R (including functions) except a handful of vectors.

One way to do this:

rm(list=ls()[! ls() %in% c("a","c")])

Where the vectors that I want to keep are named 'a' and 'c'.

Hope this helps anyone searching for the same solution!