R Deleting All Objects Except One from Environment (Example Code)

In this tutorial you’ll learn how to delete all elements but one in R programming.

Construction of Example Data

data(iris)                        # Loading some data to RStudio
data(mtcars)
xxx <- 1:5
ls()                              # Return all object names stored in global environment
# "iris"   "mtcars" "xxx"

Example: Apply rm, setdiff & ls Functions to Delete All Elements But One

rm(list = setdiff(ls(), "xxx"))   # Deleting all objects except xxx
ls()                              # Return all object names stored in global environment
# "xxx"

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top