How to Clear the Environment in R (3 Methods)


There are three methods you can use to quickly clear the environment in R:

Method 1: Clear Environment Using rm()

rm(list=ls())

Method 2: Clear Environment Using the Broom Icon

Method 3: Clear Specific Types of Objects Using lm() and class

#clear all data frames from environment
rm(list=ls(all=TRUE)[sapply(mget(ls(all=TRUE)), class) == "data.frame"])

#clear all lists from environment
rm(list=ls(all=TRUE)[sapply(mget(ls(all=TRUE)), class) == "list"])

The following examples shows how to use each of these methods in practice.

Method 1: Clear Environment Using rm()

Suppose we have an R environment with two data frames, two lists, two matrices, and two vectors:

We can use the following code to remove all objects from the envinroment:

rm(list=ls())

clear environment in R

Notice that every object in the R environment is now cleared.

Method 2: Clear Environment Using the Broom Icon

Once again suppose we have an R environment with the following objects:

We can click the broom icon to clear the entire environment:

Once we click Yes, the environment will be cleared:

Method 3: Clear Specific Types of Objects

Occasionally we may only want to clear specific types of objects from the environment in R.

For example, suppose we have an R environment with the following objects:

We can use the following code to clear only the data frames from the environment:

#clear all data frames from environment
rm(list=ls(all=TRUE)[sapply(mget(ls(all=TRUE)), class) == "data.frame"])

Notice that all of the data frames have been cleared from the environment but all of the other objects remain.

Additional Resources

The following tutorials explain how to perform other common operations in R:

How to Create a Multi-Line Comment in R
How to Delete Data Frames in R
How to Create an Empty Data Frame in R
How to Remove Specific Elements from Vector in R

Leave a Reply

Your email address will not be published.