15.1 C
London
Friday, July 5, 2024
HomeStatistics TutorialRHow to Delete Data Frames in R (With Examples)

How to Delete Data Frames in R (With Examples)

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...

The R programming language offers two helpful functions for viewing and removing objects within an R workspace:

  • ls(): List all objects in current workspace
  • rm(): Remove one or more objects from current workspace

This tutorial explains how to use the rm() function to delete data frames in R and the ls() function to confirm that a data frame has been deleted.

Delete a Single Data Frame

The following code shows how to delete a single data frame from your current R workspace:

#list all objects in current R workspace
ls()

[1] "df1" "df2" "df3" "x"

#remove df1
rm(df1)

#list all objects in workspace
ls()

[1] "df2" "df3" "x"  

Delete Multiple Data Frames

The following code shows how to delete multiple data frames from your current R workspace:

#list all objects in current R workspace
ls()

[1] "df1" "df2" "df3" "x"

#remove df1 and df2
rm("df1", "df2")

#list all objects in workspace
ls()

[1] "df3" "x"  

Delete All Data Frames

The following code shows how to delete all objects that are of type “data.frame” in your current R workspace:

#list all objects in current R workspace
ls()

[1] "df1" "df2" "df3" "x"

#remove all objects of type "data.frame"
rm(list=ls(all=TRUE)[sapply(mget(ls(all=TRUE)), class) == "data.frame"])

#list all objects in workspace
ls()

[1] "x" 

You can also use the grepl() function to delete all objects in the workspace that contain the phrase “df”:

#list all objects in current R workspace
ls()

[1] "df1" "df2" "df3" "x"

#remove all objects that contain "df"
rm(list = ls()[grepl("df", ls())])

#list all objects in workspace
ls()

[1] "x" 

Additional Resources

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

How to Create an Empty Data Frame in R
How to Append Rows to a Data Frame 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