Articles - Tips & Tricks

Clear User Interface and Free Memory in R/RStudio

Personally, to optimize the memory and work on a clean/fresh R/RStudio interface, I manage to start all my R scripts with this code:

Code R :
# Clear plots
if(!is.null(dev.list())) dev.off()
# Clear console
cat("\014") 
# Clean workspace
rm(list=ls())
# Set working directory
setwd("~/Downloads/MyScripts")


Let me explain the code line by line:
Code R :
if(!is.null(dev.list())) dev.off()

This is equivalent to click on the button clear all plots in the plots panel.


Code R :
cat("\014") 

This is identical to Ctrl+L or to click on the clear console within the Edit menu.


Code R :
rm(list=ls())

This is equivalent to click on the button clear objects from the workspace in the environment panel.


These code lines allow to clear the panels and so free memory.

Code R :
setwd("~/Downloads/MyScripts")

Here you set up your working directory, in my case (Linux Ubuntu user), I choose to use the directory Myscripts inside my Downloads directory. You could use your own path to the directory you want to use there.


I hope this code would be helpful and you would choose to use it in your scripts.

If anyone knows a code to clear the history, please let me know, i would integrate it to this article.