Remove All Objects But One from Workspace in R (Example)
In this tutorial you’ll learn how to clear all data objects from the workspace except one in the R programming language.
The tutorial will consist of the following contents:
Let’s get started:
Creation of Exemplifying Data
First, we’ll have to create some data that we can use in the examples later on:
data1 <- 1 # Create several data objects data2 <- 2 data3 <- 3
We can use the ls() function to return a character vector showing all names of data objects that are currently stored in our workspace:
ls() # Show list of objects in environment # "data1" "data2" "data3"
As you can see based on the previous output of the RStudio console, our working environment currently contains the three data objects data1, data2, and data3.
Example: Removing All Elements from Environment Except One Using rm(), setdiff() & ls() Functions
This example shows how to remove all but one specific data object from our workspace.
Let’s assume that we want to clear all data objects from our workspace except the data object data2. Then, we can apply the rm, setdiff, and ls functions as shown below:
rm(list = setdiff(ls(), "data2")) # Remove all but one
Let’s apply the ls function again to show all data objects stored in our workspace after running the previous R code:
ls() # Show list of objects in environment # "data2"
As you can see, only the data object data2 was kept in our environment.
Video, Further Resources & Summary
In case you need further explanations on the R codes of this article, you could have a look at the following video of the Statistics Globe YouTube channel. In the video, I’m explaining the topics of the present article in a live session.
Besides the video, you may read some of the other articles of this website. You can find a selection of tutorials below.
- Clear Data Object from Workspace
- Remove Multiple Data Objects Using rm Function
- Remove Rows with NA in Data Frame
- Introduction to R
In this R programming tutorial you learned how to delete and clean all elements but one. Please let me know in the comments section below, if you have further comments and/or questions.