How do I Clear the Environment in R (3 Methods)

There are three main methods to clear the environment in R. These include using the rm() function, using the environment tab in the RStudio IDE, or using the menu command within the R GUI. The rm() function is used to remove objects from the current environment, the environment tab in the RStudio IDE allows for the clearing of the environment and the removal of objects, and the menu command within the R GUI allows for the selection of the Clear Workspace option to clear the environment.


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.

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

How to Create a Multi-Line Comment in R

x