Chapter 22 Removing Objects from the R Environment

In this chapter, we will learn how to remove objects that we’ve created from the R Environment.

22.1 Conceptual Overview

When working in R, we often assign vectors, matrices, tables, data frames, models, and values to objects so that we can reference them in subsequent operations. Such objects end up in our R (Global) Environment. If you’re working in RStudio, you will see your objects in the Environment window, which is typically positioned in the upper right corner of the user interface. At times, we may wish to remove certain objects from our R Environment, which will be the focus of this chapter’s tutorial.

22.2 Tutorial

This chapter’s tutorial demonstrates how to remove objects from the R Environment.

22.2.1 Video Tutorial

As usual, you have the choice to follow along with the written tutorial in this chapter or to watch the video tutorial below.

Link to video tutorial: https://youtu.be/mUjSELUW-Ys

22.2.2 Functions & Packages Introduced

Function Package
ls base R
remove base R
rm base R
c base R

22.2.3 Initial Steps

If you haven’t already, save the file called “DataCleaningExample.csv” into a folder that you will subsequently set as your working directory. Your working directory will likely be different than the one shown below (i.e., "H:/RWorkshop"). As a reminder, you can access all of the data files referenced in this book by downloading them as a compressed (zipped) folder from the my GitHub site: https://github.com/davidcaughlin/R-Tutorial-Data-Files; once you’ve followed the link to GitHub, just click “Code” (or “Download”) followed by “Download ZIP”, which will download all of the data files referenced in this book. For the sake of parsimony, I recommend downloading all of the data files into the same folder on your computer, which will allow you to set that same folder as your working directory for each of the chapters in this book.

Next, using the setwd function, set your working directory to the folder in which you saved the data file for this chapter. Alternatively, you can manually set your working directory folder in your drop-down menus by going to Session > Set Working Directory > Choose Directory…. Be sure to create a new R script file (.R) or update an existing R script file so that you can save your script and annotations. If you need refreshers on how to set your working directory and how to create and save an R script, please refer to Setting a Working Directory and Creating & Saving an R Script.

# Set your working directory
setwd("H:/RWorkshop")

Next, read in the .csv data file called “DataCleaningExample.csv” using your choice of read function. In this example, I use the read_csv function from the readr package (Wickham, Hester, and Bryan 2024). If you choose to use the read_csv function, be sure that you have installed and accessed the readr package using the install.packages and library functions. Note: You don’t need to install a package every time you wish to access it; in general, I would recommend updating a package installation once ever 1-3 months. For refreshers on installing packages and reading data into R, please refer to Packages and Reading Data into R.

# Install readr package if you haven't already
# [Note: You don't need to install a package every 
# time you wish to access it]
install.packages("readr")
# Access readr package
library(readr)

# Read data and name data frame (tibble) object
df <- read_csv("DataCleaningExample.csv")
## Rows: 10 Columns: 6
## ── Column specification ────────────────────────────────────────────────────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (3): EmpID, Facility, OnboardingCompleted
## dbl  (2): JobLevel, Org_Tenure_Yrs
## date (1): StartDate
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# Print the names of the variables in the data frame (tibble) object
names(df)
## [1] "EmpID"               "Facility"            "JobLevel"            "StartDate"           "Org_Tenure_Yrs"     
## [6] "OnboardingCompleted"
# Print data frame (tibble) object
print(df)
## # A tibble: 10 × 6
##    EmpID  Facility  JobLevel StartDate  Org_Tenure_Yrs OnboardingCompleted
##    <chr>  <chr>        <dbl> <date>              <dbl> <chr>              
##  1 EP1201 Beaverton        1 2010-05-05            8.6 No                 
##  2 EP1202 beaverton        1 2008-01-31           10.9 No                 
##  3 EP1203 Beaverton    -9999 2017-02-05            1.9 No                 
##  4 EP1204 Portland         5 2018-09-19            0.3 No                 
##  5 EP1205 <NA>             2 2018-09-19            0.3 No                 
##  6 EP1206 Beaverton        1 2010-03-23            8.8 No                 
##  7 EP1207 beverton         1 2011-06-01            7.6 No                 
##  8 EP1208 Portland         4 2010-05-15            8.6 No                 
##  9 EP1209 Portland         3 2011-04-29            7.7 No                 
## 10 EP1210 Beaverton       11 2012-07-11            6.5 No

To demonstrate how to remove objects from the R Environment, we first need to add some more objects to our R Environment. Using the xtabs (cross-tabulation) function from base R, let’s create a two-way table called table1 from the JobLevel and Org_Tenure_Yrs variables from the df1 data frame object we just created and named.

# Create table from JobLevel and Org_Tenure_Yrs variables from df data frame
table1 <- xtabs(~ JobLevel + Org_Tenure_Yrs, data=df)

# Print table object
print(table1)
##         Org_Tenure_Yrs
## JobLevel 0.3 1.9 6.5 7.6 7.7 8.6 8.8 10.9
##    -9999   0   1   0   0   0   0   0    0
##    1       0   0   0   1   0   1   1    1
##    2       1   0   0   0   0   0   0    0
##    3       0   0   0   0   1   0   0    0
##    4       0   0   0   0   0   1   0    0
##    5       1   0   0   0   0   0   0    0
##    11      0   0   1   0   0   0   0    0

You should now see an object called table1 in your R Environment.

Next, let’s assign an arbitrary value to an object. Specifically, let’s assign the value 3 to an object called a.

# Assign the value 3 to the object a
a <- 3

# Print table object
print(a)
## [1] 3

Finally, for good measure, let’s add one more object called B to our R Environment.

# Assign the character value "example' to the object B
B <- "example"

# Print table object
print(B)
## [1] "example"

At the very least, we should now have the following objects in our R Environment: df, table1, a, and B.

22.2.4 List Objects in R Environment

In addition to viewing objects in our R (Global) Environment in the Environment window in RStudio, we can also use the ls function from base R to retrieve the names of objects that are currently in our Environment. The function is simple to use. Simply, type the name of the function (ls) without any parenthetical arguments.

# Print names of objects in R Environment
ls()
## [1] "a"      "B"      "df"     "table1"

In your R console, a list of the objects in your global environment should have printed to your Console. Next, we will learn how to remove some of these objects.

22.2.5 Remove Objects from R Environment

To remove specific objects from our R Environment, we can use the remove function from base R, which can be abbreviated as rm. To remove a specific object, just type the name of the function (remove), and as the sole parenthetical argument, type the name of the object you wish to remove. In this example, let’s remove the data frame object called df. By default, this function first searches the R Environment that is currently active.

# Remove df object from R Environment
remove(df)

Using the ls function, print the names of the objects that are currently in your R Environment. The df object should no longer be there.

# Print names of objects in R Environment
ls()
## [1] "a"      "B"      "table1"

If our goal is to remove multiple objects from the R Environment, we could apply the remove function multiple times – one for each object we wish to remove. Alternatively, we could also use the list= argument from the remove function to specify a vector of objects we wish to remove. Using the c function from base R, which combines objects into a vector, we can specify a list of the objects we wish to remove. Let’s remove the objects called table1 and a from the R Environment. Make sure to put the variable names in quotation marks (" ") when you list them as arguments within the c function.

# Remove multiple objects from R Environment
remove(list=c("table1","a"))

Using the ls function, print the names of the objects that are currently in your R Environment. The table1 and a objects should no longer appear in the R Environment.

# Print names of objects in R Environment
ls()
## [1] "B"

Finally, if you wish to remove all objects from the environment, use the remove function, and within the function parentheses, set the list argument equal to ls().

# Remove all objects from R Environment
remove(list=ls())

If you use the ls function once more without arguments, you will receive the following output, which indicates that there are no objects in the environment: character(0).

# Print names of objects in R Environment
ls()
## character(0)

22.2.6 Summary

In this chapter, we practiced applying the ls and remove functions from base R to print the names of objects in the R Environment and to remove objects from the R Environment, respectively.

References

Wickham, Hadley, Jim Hester, and Jennifer Bryan. 2024. Readr: Read Rectangular Text Data. https://CRAN.R-project.org/package=readr.