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.

0 0 vote
Article Rating
Subscribe
Notify of
guest
2 Comments
Inline Feedbacks
View all comments
satya prakash singh
satya prakash singh
4 years ago

Satya prakash singh

D_R_
D_R_
1 year ago

Thanks