R Environments
An environment is a place that stores names and their values. new.env() makes a fresh environment.
Store values with $
The $ symbol stores two values inside e. ls() then lists the names held in e.
e <- new.env()
e$name <- "Ana"
e$score <- 90
print(e$name)
print(e$score)
print(ls(e))Store and read with assign and get
assign() stores each value under a name written as text. get() reads a value back by the same text name.
e <- new.env()
assign("level", 2, envir = e)
assign("passed", TRUE, envir = e)
print(get("level", envir = e))
print(get("passed", envir = e))
print(ls(e))Check and remove a name
exists() finds score and misses bonus. rm() then removes score, and ls() shows only level left.
e <- new.env()
e$score <- 90
e$level <- 2
print(exists("score", envir = e))
print(exists("bonus", envir = e))
rm("score", envir = e)
print(ls(e))Reading a missing name fails
The inherits value FALSE keeps the search inside e alone. The missing name stops the call with an error.
e <- new.env()
print(get("nope", envir = e, inherits = FALSE))Example
store <- new.env()
store$item <- "pen"
assign("price", 5, envir = store)
print(get("price", envir = store))
print(ls(store))
rm("item", envir = store)
print(exists("item", envir = store))
print(ls(store))Key points
- new.env() makes an empty environment.
- A name after $ stores a value inside an environment.
- assign() stores a value under a name given as text.
- get() reads the value stored under a name given as text.
- exists() reports TRUE or FALSE for a name in an environment.
- rm() removes a name from an environment.
- ls() lists the names stored in an environment in sorted order.
In this example the store environment holds an item name and a price. rm() removes the item name, exists() confirms it is gone, and ls() shows only price left.
Note
An environment itself is never printed in this lesson, since printing one would show a memory address.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does ls(e) show for an environment e?