0Pricing
R Academy · Lesson

What Is an Environment in R?

Explore environments as named lists with parent pointers.

What Is an Environment in R? is a free R Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What is an Environment?

In R, an environment is a collection of named bindings (like a named list) plus a pointer to a parent environment. Every variable lives in some environment. When R looks up a name, it searches the current environment first, then walks up the parent chain.

# The global environment holds your session variables
x <- 42
cat('x is in globalenv:', exists('x', envir = globalenv()), '\n')
cat('globalenv name:', environmentName(globalenv()), '\n')

globalenv(), baseenv(), and emptyenv()

R has several built-in environments: globalenv() is your interactive workspace, baseenv() holds base R functions, and emptyenv() is the top of the chain with no parent. Every environment chain eventually terminates at emptyenv().

cat('global    :', environmentName(globalenv()),  '\n')
cat('base      :', environmentName(baseenv()),    '\n')
cat('empty     :', environmentName(emptyenv()),   '\n')
cat('parent of global:', environmentName(parent.env(globalenv())), '\n')

The Environment Chain

Each environment has exactly one parent (except emptyenv()). When R cannot find a name in the current environment, it moves to the parent, then the parent's parent, and so on. This chain is how R resolves variable names.

# Walk the parent chain from globalenv
env <- globalenv()
for (i in 1:5) {
  cat(sprintf('Level %d: %s\n', i, environmentName(env)))
  if (identical(env, emptyenv())) break
  env <- parent.env(env)
}

environment() for a Function

Every function has an associated environment — the one it was created in. environment(f) returns that environment. This is the function's enclosing environment and determines where it looks for free variables.

f <- function() 'hello'
cat('f was defined in:', environmentName(environment(f)), '\n')

# Inside a function, environment() returns its own env
show_env <- function() {
  cat('my env:', environmentName(environment()), '\n')
}
show_env()

as.list() on an Environment

as.list(env) converts an environment's bindings into a named list, which is useful for inspecting its contents programmatically. Combining it with globalenv() shows all current session variables.

a <- 10
b <- 'hello'
c_val <- TRUE
# Show current global bindings as list
bindings <- as.list(globalenv())
cat('Names in globalenv:', paste(ls(globalenv()), collapse = ', '), '\n')

ls() — List Environment Contents

ls() lists the names bound in an environment. By default it shows the global environment. Pass envir = e to inspect a specific environment. Add all.names = TRUE to include names starting with ..

my_env <- new.env(parent = emptyenv())
my_env$x <- 1
my_env$y <- 'two'
my_env$.hidden <- TRUE
cat('Default ls:', ls(envir = my_env), '\n')
cat('All names :', ls(envir = my_env, all.names = TRUE), '\n')

new.env() — Creating Environments

new.env(parent = e) creates a new empty environment with the given parent. Use emptyenv() as parent when you want a completely isolated environment with no inherited bindings.

e <- new.env(parent = emptyenv())
e$name  <- 'Alice'
e$score <- 95
cat('Names:', ls(e), '\n')
cat('Name binding:', e$name, '\n')

Environments vs Lists

Environments look like named lists but behave differently: they are always modified in place (no copy-on-modify), they have a parent, and name lookup is done by hash table (fast). Lists are copied when modified; environments are not.

# Environments are reference objects (no copy-on-modify)
e <- new.env(parent = emptyenv())
e$x <- 1
f <- e        # f points to same env, not a copy
f$x <- 99
cat('e$x after modifying through f:', e$x, '\n')

exists() and get() in an Environment

exists('name', envir = e) checks whether a name is bound in an environment (or its parents by default). get('name', envir = e) retrieves the value. Both accept inherits = FALSE to look only in the specified environment.

e <- new.env(parent = emptyenv())
e$pi_approx <- 3.14159
cat('exists pi_approx:', exists('pi_approx', envir = e), '\n')
cat('exists missing:  ', exists('missing_var', envir = e), '\n')
cat('get pi_approx:   ', get('pi_approx', envir = e), '\n')

environmentName() for Built-ins

environmentName(env) returns the human-readable name of special environments. User-created environments return '' (empty string). This helps you trace where variables were defined when debugging.

cat(environmentName(globalenv()),    '\n')  # R_GlobalEnv
cat(environmentName(baseenv()),      '\n')  # package:base
cat(environmentName(emptyenv()),     '\n')  # R_EmptyEnv
e <- new.env(parent = emptyenv())
cat('User env name: "', environmentName(e), '"\n', sep = '')

Practical: Using Environments as Caches

Because environments are modified in place, they work well as mutable caches or hash maps. Store computed results in an environment to avoid recomputing them — this is faster than modifying a list (which copies).

cache <- new.env(parent = emptyenv(), hash = TRUE)
cached_square <- function(n) {
  key <- as.character(n)
  if (exists(key, envir = cache, inherits = FALSE))
    return(get(key, envir = cache))
  result <- n^2
  assign(key, result, envir = cache)
  result
}
cat(cached_square(7), '\n')
cat(cached_square(7), '\n')  # served from cache

Quick Check

What is the top-most environment in R's environment chain — the one with no parent?

Environments: Key Takeaways

Key takeaways for R environments:

  • An environment = named bindings + parent pointer
  • globalenv() = your workspace; baseenv() = base R; emptyenv() = chain terminus
  • Name lookup walks up the parent chain until found or reaching emptyenv()
  • ls(envir=e) lists bindings; exists() checks; get() retrieves
  • Environments are reference objects — no copy-on-modify
  • new.env(parent=emptyenv()) creates an isolated environment
e <- new.env(parent = emptyenv())
assign('counter', 0L, envir = e)
for (i in 1:5) assign('counter', e$counter + 1L, envir = e)
cat('Counter:', e$counter, '\n')
cat('Env name:', environmentName(e), '\n')
cat('Bindings:', ls(e), '\n')

Frequently asked questions

Is the “What Is an Environment in R?” lesson free?

Yes — the full text of “What Is an Environment in R?” is free to read here on the web, and the R Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the R Academy course, upgrade to CoddyKit PRO.

What will I learn in “What Is an Environment in R?”?

Explore environments as named lists with parent pointers. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start R Academy?

No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “What Is an Environment in R?” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this R Academy lesson?

Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. What Is an Environment in R?
  2. Lexical Scoping Rules
  3. Global vs Local Scope
  4. Creating and Inspecting Environments
← Back to R Academy