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