How to clear the R environment




How can I clean the R environment both using RStudio and the R console?



I think you're looking for

rm(list = ls())

See the rm docs for more info.


rm will remove all of the objects that are stored in your global environment (which may be what you want) but will not unload any of the packages that you have loaded. 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.

EDIT: As @prosoitos correctly points out below, restarting your R session will only have the desired effects if you are not saving your workspace to your .Rdata file (which is typically not recommended)


Thanks very much for your response.


Thank you very much for your response

rm(list = ls(all.names = TRUE)) #will clear all objects includes hidden objects.
gc() #free up memrory and report the memory usage.

Kindly refer to What is the difference between gc() and rm().


As a few people have already mentioned, to clear your global workspace, you can use

rm(list = ls())

However, I would suggest if you are using this regularly, you are probably doing it wrong. Instead, I would change the settings to never save your workspace. You can do this in RStudio

This means when you restart R via Ctrl+Shift+F10, your workspace is cleared.

Under Linux, I use the following alias when accessing R via the command line:

alias R="R --no-save --no-restore-data --quiet"


I second csgillerspie and I would add the advice of restarting R often as you work (once you have set the option not to save any .RData file), to make sure that you are really running what is in your script.


(Considering you are not autosaving and autoloading any .RData file.)


Thank you very much for your response


Thank you very much for your help


Thank you very much for helping