Delete Data Frame in R

It is good practice to keep a clean workspace by removing objects that are no longer being used. This is especially true if you have saved multiple large data frames in the course of your analysis.

Let’s say you have a workspace with five objects stored, and looks like this:

# List all objects in the workspace
> ls()
[1] "first_name" "last_name"  "new_df"     "players"    "score"     

The ls() function returns a vector listing lists all the objects (vectors, data frames, etc) in your current workspace.

There are a few ways to remove data frames and other objects from your workspace:

    # Remove these three objects
    > rm("first_name", "last_name", "new_df")

    # Or remove objects listed in a vector
    > rm(list = c("first_name", "last_name", "new_df"))

    # Or remove all files from your workspace
    > rm(list = ls())

    # Or remove vectors programmatically.  Delete objects with underscore in name
    > rm(list = ls()[grepl("_", ls())])

The rm() function removes specified objects, similar to the rm command in UNIX which removes files from a director. Notice the power of vectors showing up again; since rm() can accept a set of object names in a vector, we can use vector logic like in the last example to programmatically remove specific objects.

Leave a Reply

1 Comment on "Delete Data Frame in R"


satya prakash singh
satya prakash singh
9 months 5 days ago

Satya prakash singh