Enjoy R: A useful function for clearing the workspace

Today I was coding with my supervisor, and we actually had a bunch of things saved in our workspace which we wanted to get rid of. The annoying matter was that we aimed to delete almost all the workspace and keep only a couple of functions. R has a fast way to clear all the workspace, which is rm(list = ls()) (actually in RStudio you can also click on the yellow brum at the top of your “Environment” section). Since we wanted to keep something, this was not an option. We were about to start typing the list of names of all the functions that had to be deleted and pass it to rm(), when we had an idea: why not building a more elegant and less tedious method for doing this? Let’s think of what ls() is: it is a vector of strings, no other than that. Each string corresponds to the name of an object of your workspace. Hence, what rm() demands is a vector of names. It is straightforward now: we can use the subset of the vector ls() which does not include the names of the objects we want to keep. To make it more general and hence more usable to others, here you find a function that does the trick. The function is to be used in the Global Environment, which is the one you’re more likely to be working in. The inputs are:

  • x which is the vector of names of the variables we want to keep in our workspace;
  • keep_this_function which is set to TRUE by default, since we don’t want our cool function to disappear from our workspace 😉

Following the code:
rm_all_but <- function(x, keep_this_function = TRUE) {

      if(keep_this_function) { x <- c("rm_all_but", x) }

      rm(list = ls(pos = ".GlobalEnv") [ !(ls(pos = ".GlobalEnv") %in% x)], pos= ".GlobalEnv")


Let’s try it on my workspace:

a=1 ; b=2; c=3; d=4
[1] "a" "b" "c" "d" "rm_all_but"

rm_all_but(x = c("a", "b"))

ls() # were "c" and "d" deleted?
[1] "a" "b" "rm_all_but"

Yes! 😀


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: