15.1 C
London
Friday, July 5, 2024
HomeRImport & Export Data in RHow to Clear the Environment in R (3 Methods)

How to Clear the Environment in R (3 Methods)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories