The Analogy: A Hotel's Front-Desk Key Board
Picture the key board behind a hotel's front desk: a single wooden rack of labelled pigeonholes, one per room, each holding the key for that room. The board is a physical object that sits in exactly one place. Every clerk on shift walks up to the same board, reads the same labels, and takes or returns keys from the same slots. Nobody carries a personal copy of the board around; there is one board, and everyone works against it directly. When a clerk needs the key for room 102, they find the pigeonhole labelled "room102" and take whatever is hanging in it right now.
Hanging a key in a labelled slot is how the board binds a name to a value. The label "room102" is the name; the key currently in that pigeonhole is the value. Looking a name up means reading whatever hangs in its slot at this moment, and re-hanging a different key in the same slot changes what that name refers to without moving the label. An empty slot is a name that exists on the board but holds nothing yet. This is exactly what an R environment does: it is a container that maps names to values, and assign, get, and exists are the acts of hanging a key, reading a slot, and checking whether a slot is present.
A large hotel has more than one board. Each floor's service desk has its own small board for that floor's rooms, and behind it, at the head office, sits a master board with everything. When a bellhop looks for a key that is not in the floor board's slots, they do not give up: they walk up to the master board and look there. That climb from the local board to its parent, and on up until the key is found or the boards run out, is lexical scoping. Every environment has a parent environment, and a name that is not bound locally is searched for in the parent, then the parent's parent, all the way to the global board and the empty environment beyond it.
The trouble the board causes is the trouble of shared mutable state. Because there is one physical board and not a copy per clerk, a change one clerk makes is seen instantly by every other clerk -- which is the point, until it is the problem. If a clerk quietly re-hangs the key in the "room102" slot while another clerk is midway through checking a guest in, the second clerk reads a slot that changed underneath them and hands out the wrong key. R environments behave the same way: unlike almost everything else in R, they are not copied when you pass them to a function or assign them to a new name. Two names for one environment are two clerks at one board, and a write through either is a write both of them see. That single fact -- reference semantics in a copy-on-modify language -- is the source of most environment surprises and the engine behind closures.
Syntax or Core Structure
An environment is created with new.env(). You bind names into it with assign() or the $ operator, read them with get(), and test for them with exists(). The decisive difference from a list is that an environment is passed by reference: a function handed an environment mutates the caller's own environment, not a copy.
board <- new.env()
assign("room101", "free", envir = board)
assign("room102", "free", envir = board)
assign("room103", "free", envir = board)
# check_in mutates the SAME board it is handed -- no copy is made
check_in <- function(env, room) {
assign(room, "booked", envir = env)
invisible(NULL)
}
check_in(board, "room101")
writeLines(sprintf("%-14s: %s", "keys on board", paste(sort(ls(board)), collapse = " ")))
writeLines(sprintf("%-14s: %s", "room101", get("room101", envir = board)))
writeLines(sprintf("%-14s: %s", "room103 set",
if (exists("room103", envir = board, inherits = FALSE)) "TRUE" else "FALSE"))
writeLines(sprintf("%-14s: %s", "room900 set",
if (exists("room900", envir = board, inherits = FALSE)) "TRUE" else "FALSE"))
Output:
keys on board : room101 room102 room103
room101 : booked
room103 set : TRUE
room900 set : FALSE
The call check_in(board, "room101") returned nothing, yet room101 now reads booked: the function reached through the reference and changed the caller's board. Had board been an ordinary list, check_in would have mutated a private copy and the original would still read free. ls(board) lists the slot labels, sorted here so the order is stable, and exists with inherits = FALSE checks only this board -- not its parents -- which is why room900, bound nowhere, comes back FALSE.
Technical Depth: Closures, S3, and S4
Closures: functions that carry their own board
When a function is defined, it captures the environment it was created in, and it keeps that environment alive for as long as the function exists. A function that returns another function therefore hands back a private board that only the returned function can reach. This is a closure, and it is the mechanism behind stateful functions, function factories, and most of R's higher-order tooling. The superassignment operator <<- writes to that captured board rather than creating a new local binding.
make_counter <- function(start = 0) {
count <- start
function() {
count <<- count + 1 # writes to the captured environment, not a local copy
count
}
}
tickA <- make_counter(0)
tickB <- make_counter(100)
a <- c(tickA(), tickA(), tickA())
b <- c(tickB(), tickB())
writeLines(sprintf("%-18s: %s", "counter A ticks", paste(a, collapse = " ")))
writeLines(sprintf("%-18s: %s", "counter B ticks", paste(b, collapse = " ")))
writeLines(sprintf("%-18s: %s", "A and B separate",
if (!identical(environment(tickA), environment(tickB))) "TRUE" else "FALSE"))
writeLines(sprintf("%-18s: %d", "A state via get", get("count", envir = environment(tickA))))
Output:
counter A ticks : 1 2 3
counter B ticks : 101 102
A and B separate : TRUE
A state via get : 3
Each call to make_counter builds a fresh environment, so tickA and tickB carry entirely separate boards -- identical on their environments is false, and A counting to 3 leaves B untouched at 102. The line A state via get reaches into A's private environment from the outside and reads the count binding directly, showing that the closure's state is a genuine environment you can inspect, not hidden magic.
S3: dispatch by a class label
S3 is R's lightest object system. An object becomes a member of a class simply by having its class attribute set, and a generic function like print or area dispatches to a method named generic.class. There is no formal class definition and no enforced structure; the class attribute is a label, and dispatch is a name lookup.
area <- function(shape) UseMethod("area")
area.circle <- function(shape) pi * shape$r^2
area.square <- function(shape) shape$side^2
area.default <- function(shape) stop("unknown shape")
circ <- structure(list(r = 2), class = "circle")
sq <- structure(list(side = 3), class = "square")
writeLines(sprintf("%-16s: %.4f", "area of circle", area(circ)))
writeLines(sprintf("%-16s: %d", "area of square", as.integer(area(sq))))
writeLines(sprintf("%-16s: %s", "circ class", class(circ)))
writeLines(sprintf("%-16s: %s", "circ is list",
if (inherits(circ, "list")) "TRUE" else "FALSE"))
Output:
area of circle : 12.5664
area of square : 9
circ class : circle
circ is list : FALSE
Calling area(circ) routes to area.circle purely because circ carries the class label circle; area(sq) routes to area.square the same way, and an object with no matching method falls to area.default. The last line is the sharp edge of S3: circ is built on a list, but inherits(circ, "list") is FALSE because inherits consults the class attribute, which someone set to circle alone. The underlying storage type and the class label are different things, and S3 trusts the label completely.
S4: formal classes with validity
S4 is the formal system. Classes are declared with setClass, their fields (called slots) have declared types, and a validity function can reject malformed objects at construction. Generics are declared with setGeneric and methods with setMethod. The cost is ceremony; the benefit is that an S4 object cannot silently be the wrong shape.
setClass("Sensor",
slots = c(id = "character", reading = "numeric"),
validity = function(object) {
if (object@reading < 0) "reading must be non-negative" else TRUE
})
invisible(setGeneric("status", function(object) standardGeneric("status")))
setMethod("status", "Sensor",
function(object) if (object@reading > 100) "HIGH" else "OK")
s <- new("Sensor", id = "S1", reading = 42)
bad <- tryCatch(new("Sensor", id = "S2", reading = -5),
error = function(e) "rejected")
writeLines(sprintf("%-16s: %s", "slot names", paste(slotNames("Sensor"), collapse = " ")))
writeLines(sprintf("%-16s: %s", "sensor id", s@id))
writeLines(sprintf("%-16s: %d", "sensor reading", as.integer(s@reading)))
writeLines(sprintf("%-16s: %s", "status", status(s)))
writeLines(sprintf("%-16s: %s", "is a Sensor", if (is(s, "Sensor")) "TRUE" else "FALSE"))
writeLines(sprintf("%-16s: %s", "negative reading", bad))
Output:
slot names : id reading
sensor id : S1
sensor reading : 42
status : OK
is a Sensor : TRUE
negative reading: rejected
The valid sensor is built, reports its slots and status, and confirms its class through is. The attempt to build a sensor with a reading of -5 never produces an object at all: the validity function returns an error string, new raises it, and tryCatch turns it into the word rejected. That refusal at construction is the guarantee S3 cannot make -- an S3 object will happily hold a negative reading because nothing checks it.
Choosing between S3 and S4
The two systems trade ceremony against safety, and the right choice depends on how much a wrong-shaped object would cost you.
| Aspect | S3 | S4 |
|---|---|---|
| Class definition | None; set the class attribute | Formal, via setClass |
| Field types | Unchecked | Declared per slot |
| Validity checks | None built in | Validity function at construction |
| Dispatch | Method name generic.class | setGeneric plus setMethod |
| Field access | Ordinary list indexing | The @ operator on slots |
| Best when | Quick, informal objects | Structure must be guaranteed |
Real World Example: A Running-Statistics Accumulator
A monitoring script needs to keep a running total and mean of readings as they stream in, without holding every reading in memory. The natural R design is a factory that returns a bundle of closures sharing one private environment: an add that folds in a new reading, a count and sum and mean that report, and a reset. The private environment is the accumulator's state, and because all the returned functions close over the same environment, they stay in sync. The same reference semantics that make this elegant also lay a trap, which the second half of the program springs deliberately.
make_accumulator <- function() {
total <- 0
n <- 0
list(
add = function(x) { total <<- total + x; n <<- n + 1; invisible(NULL) },
count = function() n,
sum = function() total,
mean = function() if (n == 0) NA_real_ else total / n,
reset = function() { total <<- 0; n <<- 0; invisible(NULL) }
)
}
acc <- make_accumulator()
for (x in c(10, 20, 15, 25, 12, 8)) acc$add(x)
writeLines(sprintf("%-20s: %d", "readings added", acc$count()))
writeLines(sprintf("%-20s: %d", "running sum", acc$sum()))
writeLines(sprintf("%-20s: %.2f", "running mean", acc$mean()))
# the trap: assigning to a new name does NOT copy the accumulator
alias <- acc
alias$add(30) # mutates the SAME environment acc uses
writeLines(sprintf("%-20s: %d", "count after alias", acc$count()))
writeLines(sprintf("%-20s: %d", "sum after alias", acc$sum()))
acc$reset() # reset through acc...
writeLines(sprintf("%-20s: %d", "sum after reset", acc$sum()))
writeLines(sprintf("%-20s: %d", "alias sum too", alias$sum())) # ...alias sees it too
Output:
readings added : 6
running sum : 90
running mean : 15.00
count after alias : 7
sum after alias : 120
sum after reset : 0
alias sum too : 0
The first three lines are the accumulator working as intended: six readings folded in, a running sum of 90, and a mean of 15.00, all held in a single environment rather than a growing vector. This is a genuinely good use of closures -- the state is encapsulated, the interface is small, and no reading is retained after it is added.
Then the trap. Writing alias <- acc looks like it makes a second, independent accumulator, and in a copy-on-modify language that intuition is usually right. But acc is a list of closures, and those closures hold a reference to one environment. Copying the list copies the references, not the environment, so alias and acc are two names for the same board. Adding 30 through alias pushes acc's count to 7 and its sum to 120, and resetting through acc zeroes the sum that alias reports as well. Two names, one state.
The design has real flaws worth naming plainly. The most dangerous is exactly the aliasing shown: because the accumulator's identity lives in a shared environment, alias <- acc silently creates a second handle to the same state, and any code that assumes assignment made an independent copy -- the overwhelmingly common assumption in R -- will corrupt data across what it believes are separate objects. There is no true encapsulation either: the "private" total and n live in environment(acc$add), which any caller can reach and overwrite from outside, and nothing calls lockEnvironment to prevent it. Finally, <<- searches outward for an existing binding, so if the enclosing total were ever removed, the operator would keep climbing and could create or clobber a total in the global environment instead of failing -- a silent leak of state into the wrong board.
Common Mistakes
- Expecting an environment to be copied on assignment. Environments -- and closures that hold them -- are passed and assigned by reference.
e2 <- e1gives you a second name for one environment, not a duplicate, so a write through either is seen by both. This is the single biggest surprise when moving from R's usual copy-on-modify values to environments.
- Reaching for
<<-when you mean<-. The superassignment operator does not assign locally; it searches enclosing environments for an existing binding and writes to the first one it finds. Used by accident inside a function, it can silently modify a variable in an outer scope or even the global environment instead of creating the local you intended.
- Assuming
<<-creates the binding where you expect. If no enclosing environment has the name,<<-creates it in the global environment, not next to the function. A misspelled name on the left of<<-therefore leaks a new global rather than raising an error, which is very hard to trace later.
- Trusting an S3 object's structure because it dispatched. S3 dispatch checks only the class attribute, which is a label anyone can set to anything. An object labelled
circleneed not have anrfield, andarea.circlewill fail deep inside rather than at a clean validity boundary. S3 gives you dispatch, not guarantees.
- Defining an S3 method with a signature that does not match the generic. If the generic is
area(shape)but you writearea.circle <- function(x), dispatch still works but argument-name-based calls break, andNextMethodcan misbehave. Keep the method's first argument named like the generic's.
- Forgetting that
inheritsandclassread the attribute, not the storage type. A list withclass = "circle"reports its class ascircleandinherits(x, "list")isFALSE. If you need the underlying type, usetypeoforis.list;classandinheritsanswer a different question.
- Skipping the validity function in S4 and validating by hand later. The whole point of S4 is to reject malformed objects at construction. Scattering manual checks through downstream code instead means an invalid object can exist and travel before anything notices. Put the invariant in the
validityfunction wherenewenforces it.
- Mutating an S4 slot in place and expecting reference semantics. S4 objects are ordinary copy-on-modify values, not environments. Writing
obj@reading <- 5inside a function changes a copy; the caller's object is untouched unless you return the modified object. Only environments give you reference mutation.
- Leaving a closure's environment open when it should be sealed. A closure's captured environment is reachable and writable from outside via
environment(fn). If the state is meant to be private, calllockEnvironment(environment(fn), bindings = TRUE)so callers cannot reach in and corrupt it; otherwise "private" is only a convention.
Best Practices
- Reach for an environment only when you genuinely need reference semantics -- shared mutable state, a hash-map-like store, or a closure's private data. For everything else, a plain list keeps the safe copy-on-modify behaviour that makes R code easy to reason about.
- Prefer a local
<-and an explicit return over<<-wherever you can. When you do need<<-, make sure the binding it targets is created in the enclosing scope first, so the operator finds it rather than leaking a global.
- Choose S3 for small, informal objects and S4 when a wrong-shaped object would be costly. Do not mix systems on one class without a clear reason; the dispatch rules interact in ways that are hard to predict.
- Always write an S3 constructor that sets the class and checks the essential fields, rather than setting the class attribute inline at call sites. A single constructor gives you one place to enforce shape and one place to fix it.
- Give every S4 class a validity function that encodes its invariants, and let
newenforce them. A class whose only guarantee is its slot types is barely more than a list.
- Access S4 slots through the
@operator and S3 fields through$, and never reach into a closure's environment from outside except to inspect it in debugging. Treating internals as public makes every refactor a breaking change.
- Seal a closure's environment with
lockEnvironmentwhen the state must stay private, so the encapsulation is enforced by R rather than trusted to callers.
- Document that closure-based objects and environments are shared on assignment. A one-line comment at the factory saves the next reader from the aliasing trap, which no type signature in R will warn them about.
Practice Exercises
- Create an environment with
new.env(), bind three names into it, then write a function that takes the environment and doubles one of the values. Call it and confirm from outside that the original environment changed, demonstrating reference semantics. Then repeat with a list and show the list did not change.
- Write a
make_counterfactory that returns a counter closure, create two counters, and advance them different numbers of times. Useenvironment()andget()to read each counter's private state directly, andidentical()to prove the two counters hold separate environments.
- Define an S3 class
accountwith a constructor, aprint.accountmethod, and adepositgeneric with anaccountmethod. Build an account, deposit into it, and print it. Then set the class attribute of a plain list toaccountby hand and show how it breaks when a method touches a missing field.
- Define an S4 class
Temperaturewith a numericcelsiusslot and a validity function that rejects values below absolute zero (-273.15). Construct a valid temperature, then attempt an invalid one insidetryCatchand confirm the construction is rejected before any object exists.