How can data frames be deleted in R?

Data frames are a popular data structure in R that allows for the organization and manipulation of data. In order to delete a data frame in R, there are a few different methods that can be used. One way is to use the “rm()” function, which removes objects from the current environment. This can be done by specifying the name of the data frame as the argument in the function. Another method is to use the “detach()” function, which detaches the data frame from the current environment, effectively deleting it. Additionally, if the data frame is stored as a variable, it can be deleted using the “rm()” function with the variable name as the argument. It is important to note that deleting a data frame in R is permanent and cannot be undone, so caution should be taken when using these methods.

Delete Data Frames in R (With Examples)


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

x