Immutability vs.
Reassignment
Explore how R handles values that never change and names that can point to new data: two ideas that shape how every R program behaves.
What Is a Value in R?
Every piece of data you create in R: a number like 42, a string like "hello", or a vector like c(1, 2, 3): is stored as a value in memory. Think of a value as a sealed box: once R creates it, the contents of that particular box never change.
What Is a Name (Variable)?
When you write x <- 42, you are not putting 42 "inside" x. You are creating a name called x and attaching it like a label to the value 42 that already exists in memory.
Why Does This Matter?
Understanding how R separates names from values helps you predict program behaviour, avoid bugs, and reason about what your code is actually doing when it "changes" a variable.
The Core Rule: Immutability
The Core Rule: Reassignment
Immutability vs. Reassignment
| Immutability | Reassignment | |
|---|---|---|
| What it governs | Values (data) | Names (variables) |
| Rule | Values cannot be changed in place | Names can point to new values anytime |
| Analogy | A sealed envelope | Moving a sticky note to a new envelope |
| Who decides? | R's internal engine | You, the programmer |
| Visible effect | Old data is never corrupted | Variable appears to "change" |
How to Think Through R Code
Example 1: Simple Reassignment
Example 2: Two Names, One Value
Example 3: Vectors and Indexing
R's Secret: Copy-on-Modify
R is smart about immutability. It does not copy a value the moment you create a second name for it. Instead, it waits until you try to "modify" one copy: only then does R create a new value. This is called copy-on-modify.
Functions and Immutability
The Exception: Environments
Almost everything in R is immutable. The main exception is environments: special objects that are modified in place. But for day-to-day R coding, you rarely manipulate environments directly.
Common Mistakes
Summary at a Glance
| Concept | What Happens | Example |
|---|---|---|
| Immutability | Values never change in place | c(1,2,3) stays as-is |
| Reassignment | Name moves to new value | x <- 20 after x <- 10 |
| Copy-on-Modify | R copies only when needed | b[1] <- 99 triggers copy |
| Function safety | Local copy inside functions | Caller's data is untouched |
Question 1 of 5
When you write x <- x + 1 in R, what actually happens?
Question 2 of 5
Code:
a <- c(1, 2, 3)
b <- a
b[1] <- 99
print(a)
What does print(a) output?
Question 3 of 5
Immutability in R means:
Question 4 of 5
Code:
double_it <- function(n) {
n <- n * 2
return(n)
}
x <- 7
y <- double_it(x)
print(x)
What does print(x) output?
Question 5 of 5
Which of the following is mutable (can be modified in place) in R?