2024-09-15

Learn R - How to clean the "working memory" in R

When you want to delete all the variables and objects in the current workingspace in R for whatever reason, you can use rm().

For me, it happens when I am running lines of code in command lines to do quick, exploratory, pilot types of analyses. Some variables (or objects) defined earlier could create a mess if the existing variables have the same name. The old value previously set could introduce a wrong initial value. Then, the code returns some value without any errors, but it could be just wrong! The worse is that I don't even know what just happened...

How can we fix it quickly? By cleaning the current workspace (which is generally the global environment. If you don't know about "environments" in R, don't worry about them for now).

This is what I usually do:

> rm(list=ls())

It cleans all the objects in the workingspace.

Let's see if there is any previous objects:

> ls()
character(0)

Now it's a clean slate! So no worries about using wrong inital values for variables. It must return errors if the value is not correctly set before using it.

Enjoy coding in R!