Environments

What is an “Environment”

Advanced Reading

Every R command is executed in a particular environment. Conceptually, you can think of R environments as collections of the objects that R currently has stored in working memory. At this point, you only need to consider one of R’s several types of environment: the Global Environment.

Global Environment

The global environment is the highest-level environment that R maintains. This environment contains all of the objects you define in your R session. The interactions described below all interface with the global environment. The Environment tab in RStudio shows the contents of the global environment, by default.

Interacting with the Environment

We can use the ls() function to list the contents of the current environment.

## The environment is empty because we haven't defined any objects
ls()
character(0)
## Create some objects
x <- 7
y <- 8
z <- 9
name <- "bob"
age <- 38

## View the updated contents of the environment
ls()
[1] "age"  "name" "x"    "y"    "z"   

The rm() function will remove an object from the environment. The following code will remove x from the environment.

rm(x) # Remove 'x' from the environment
ls()  # Check the results
[1] "age"  "name" "y"    "z"   
Practice
  1. Use the ls() function to view the contents of the environment.
  2. Use the rm() function to remove age from the environment.
  3. Use ls() to check your work.
ls()
[1] "age"  "name" "y"    "z"   
rm(age)
ls()
[1] "name" "y"    "z"   
Back to top