6.2 What Is an R Object?

R RUNTIMESTATUS: STABLELEVEL: INTROREVIEWED: 2026-11-18
Before this page How R Executes Code

6.2.1 Motivation

Every value in an R session is an object on the heap. The number 1, the string "a", and a data frame with a million rows are all heap objects. From R code there is no exception for small values: no bare machine integer or float is visible outside an object. Inside, the byte-code engine keeps scalars unboxed on its stack, as the scalars section below describes.

Inside the C source of R, one pointer type describes every object: the SEXP. This page stays at the level that R code can observe. The byte-level C layout has its own page.

These rules decide how much memory a pipeline uses, and when an assignment is free and when it copies megabytes. For my projects they decide something more basic: what “one object” means. That definition controls what can move between threads and what must not.

6.2.2 Mental model

Think of an R object as a shipping box with labels glued to the outside. The box holds the data. The labels hold metadata about the data. R calls the labels attributes. The box and its labels travel together, always.

In more precise terms, every R object has three parts:

  1. A header. It records the object type and bookkeeping for the garbage collector. A vector keeps its length right after it.
  2. An attribute pairlist. A pairlist is a linked list of tag and value pairs. It is empty for most objects.
  3. A data payload. For an integer vector this is a block of 4-byte integers. For a list it is a block of pointers to other objects.
header: type, GC bits, reference count attributes: names, dim, class data payload: the values themselves a data frame is a list attributes: names, class, row.names x: integer vector y: character vector a classed list of column vectors, not a new object type

Every R object is a header, an attribute pairlist, and a payload. A data frame is a list of column vectors plus attributes.

Hold this picture. The rest of the page fills in each part.

6.2.3 Mechanism

Atomic vectors

The basic data objects in R are atomic vectors. There are six atomic types:

typeof() Example One element is
logical c(TRUE, NA, FALSE) a 4-byte integer with three legal values
integer 1:10 a 4-byte signed integer
double c(1, 2.5) an 8-byte IEEE 754 float
complex 1+2i two doubles, real and imaginary
character c("a", "b") a pointer to a cached string object
raw as.raw(255) one byte

“Atomic” here means the elements all have one type and are not themselves R objects. An element of a double vector is 8 bytes inside the payload, not a separate heap object. Character vectors are the one exception. Their elements are pointers to string objects, described under internal mechanics below.

typeof() reports which of these payloads an object has. Keep that function in mind. It becomes the main diagnostic tool later on this page.

Scalars are vectors of length one

R has no scalar type. The value 1 is a double vector that holds one element:

typeof(1)     # "double"
length(1)     # 1
is.vector(1)  # TRUE
1             # [1] 1

The [1] in printed output is an element index. R prints most vectors with indices, and a scalar is just a very short vector. This design comes from the S language. Arithmetic, comparison, and most builtins are defined on whole vectors. A scalar is the degenerate case, not a separate concept.

The design has a runtime cost. The expression x + 1 allocates a fresh vector for the result, even when x has length one. In the AST interpreter a loop that adds numbers one at a time therefore allocates one heap object per iteration. The bytecode VM avoids most of that by keeping scalar values unboxed on its stack and in variable bindings: in R 4.6.1 a compiled s <- s + i loop of ten million iterations ran without a single garbage collection, while the same loop run by the AST walker triggered 87.

Lists are generic vectors

A list is also a vector. The R Language Definition calls it a generic vector. Its payload is a block of pointers, one per element:

l <- list(1L, "a", c(TRUE, FALSE))
typeof(l)  # "list"
length(l)  # 3

Each element can be any R object. An element can even be another list. Note what this means for memory: a list never contains its elements. It points at them. The integer 1L above is its own heap object, and the list holds its address. This pointer structure is why one data frame is really a graph of objects. The example section below walks that graph.

Attributes

Attributes are the metadata mechanism. Any object can carry a set of named values in its attribute pairlist. Read them with attributes() and write them with attr() or helper functions:

v <- 1:6
attributes(v)         # NULL
names(v) <- c("a", "b", "c", "d", "e", "f")
attributes(v)         # $names: "a" "b" "c" "d" "e" "f"

Several attributes get special treatment from the interpreter (dimnames, tsp, comment and row.names among them). This page uses three of them:

  • names labels the elements and enables subsetting by name, as in v["c"].
  • dim gives a vector a shape. A dim of c(2L, 3L) makes a 2 by 3 matrix.
  • class is the dispatch tag for the S3 object system. Generic functions such as print() read it and select a method, for example print.data.frame.

Watch what dim does to a plain integer vector:

v <- 1:6
dim(v) <- c(2L, 3L)
v
#      [,1] [,2] [,3]
# [1,]    1    3    5
# [2,]    2    4    6

No element changed. The payload holds the same six integers in the same order, the attribute pairlist gained a dim, and the print method changed its behavior in response. Here R first copies the compact sequence 1:6 into an ordinary vector, because compact sequences are marked not mutable; on an ordinary vector with one reference, dim<- works in place.

6.2.4 Matrices, data frames, and factors are not new kinds

R appears to have many container types: matrices, arrays, data frames, factors, time series. Every one of them is an atomic vector or a list with attributes attached. The costume changes, and the body underneath is always one of the seven vector types above.

typeof() reports the body. class() reports the costume:

m <- matrix(1:6, nrow = 2)
typeof(m)   # "integer"
class(m)    # "matrix" "array"

df <- data.frame(x = 1:3, y = c("a", "b", "c"))
typeof(df)  # "list"
class(df)   # "data.frame"

f <- factor(c("low", "high", "low"))
typeof(f)   # "integer"
class(f)    # "factor"
levels(f)   # "high" "low"

Read each pair:

  • A matrix is an integer vector plus a dim attribute. Since R 4.0.0, class() on a matrix returns both "matrix" and "array".
  • A data frame is a list of equal-length column vectors, plus names, row.names, and class = "data.frame".
  • A factor is an integer vector of level codes, plus a levels character vector and class = "factor". The value 2L means “the second level”.

Strip the costume and the body is exposed:

unclass(f)  # 2 1 2, with a levels attribute still attached

GNU R produces the typeof() and class() outputs shown above. The rrs project implements matrices, data frames, and factors the same way: classed vectors and lists on top of the attribute machinery, with no new object kind. Differential tests against pinned GNU R 4.6.1 confirm the observable behavior matches.

This fact simplifies any R-compatible runtime. The runtime must implement about two dozen core object types and one attribute mechanism. It gets matrices, data frames, and factors without any new object type, because those exist only as conventions that library code and a few builtins agree on.

6.2.5 A simple example

Walk the full object graph for one small data frame:

df <- data.frame(x = 1:3, y = c("a", "b", "c"))

The name df is a binding in the global environment. The binding points to a list object. The list payload holds two pointers, one per column. The attribute pairlist hangs off the same list object and holds names, row.names, and class. Each of those attribute values is itself a small vector object. The character column holds three pointers to cached string objects.

flowchart TD
  b["binding: df"] --> l(["list, length 2"])
  l -->|"column 1"| x(["integer vector: 1 2 3"])
  l -->|"column 2"| y(["character vector,<br/>length 3"])
  l -->|"attributes"| a(["pairlist: names,<br/>class, row.names"])
  a --> nm(["names: 'x' 'y'"])
  a --> cl(["class: 'data.frame'"])
  a --> rn(["row.names: c(NA, -3),<br/>compact form of 1:3"])
  y -->|3 pointers| cs(["CHARSXPs<br/>'a', 'b', 'c'"])
  sc[("global string<br/>cache")] --- cs

One small data frame is a graph of about a dozen heap objects, and its strings live in a process-wide cache.

Count the nodes: one list, two column vectors, three pairlist cells, three attribute value vectors, and several string objects. A data frame is a graph, not one block of memory, so any operation that claims to “send a data frame somewhere” must either walk this whole graph or share it in place.

6.2.6 Copy-on-modify

R behaves as if assignment copies the value:

x <- c(1, 2, 3)
y <- x
y[1] <- 10
x           # 1 2 3, unchanged

A real copy at every assignment is too slow for large data, so R delays it. The rule is copy-on-modify: assignment makes both names point at one object, and the copy happens later, at the first write through either name.

The function tracemem() makes the moment of the copy visible. It prints a line whenever the traced object is duplicated:

x <- c(1, 2, 3)
tracemem(x)
#> [1] "<0x55a4c8f0a3e8>"

y <- x        # silence: no copy, two names share one object
y[1] <- 10    # tracemem[0x55a4c8f0a3e8 -> 0x55a4c8f0b158]: the copy happens now
x[2] <- 5     # silence again: x is now sole owner, R modifies in place

The rules that decide when a copy happens:

  • Plain assignment, argument passing, and list insertion never copy. They create new references to the same object.
  • A write through a name copies the object first if any other reference exists. This is the tracemem line above.
  • A write to an object with exactly one reference mutates the payload in place. No copy, no allocation of a new vector.

The object header stores the reference count. Before R 4.0.0 the header kept a cruder counter, NAMED, that almost never went back down. In its classic form it took the values 0, 1 and 2, where 2 meant “shared” (R 3.5.0 and 3.6.0 raised the ceiling to 3 and then 7), so R made some copies that were not necessary. R 4.0.0 replaced it with reference counting, which drops when a reference goes away, so more writes qualify for in-place mutation. The copy-on-modify page covers the counter in depth.

One caution: copy-on-modify applies to vectors, lists, and most other values. Environments are the main exception, and external pointers behave the same way. An environment is mutated in place and every reference observes the change. That reference behavior is the subject of the environments page.

6.2.7 Internal mechanics: strings and the global cache

Character vectors need a closer look, because their payload is special. Each element is a pointer to a separate string object. R Internals names that object type CHARSXP.

R interns these strings. A process-wide hash table, the string cache, holds one CHARSXP per distinct string and encoding, with a few exceptions such as NA_STRING. When code creates the string "apple", R first searches the cache. If the string exists, R reuses the pointer. If not, R allocates one CHARSXP and registers it:

x <- c("apple", "banana")
y <- "apple"
# x[1] and y[1] point at the same cached string object

The benefits are large. A column with a million repeats of ten labels stores ten strings, not a million. Equality checks between cached strings can compare pointers instead of bytes.

The cost shows up under concurrency. The cache is one process-global mutable table, and every string creation on any thread must search and sometimes update it. That makes it the kind of shared mutable state that this corpus exists to reason about.

6.2.8 Relevance to my work

An R-compatible runtime does not get to choose different object semantics. Package code observes typeof(), class(), attribute round-trips, and the timing of copies. Tests and user scripts encode those observations. The rrs interpreter treats pinned GNU R 4.6.1 as the specification and runs differential tests against it for exactly this reason.

The second consequence follows from the object graph. “Move this data frame to another thread” is not one operation on one block. The graph spans the list, the columns, the attribute vectors, and string objects inside a shared cache. A runtime has two options. It can walk the graph and serialize a copy across the boundary. Or it can share the memory and then prove that no thread mutates what another thread reads.

Sharing is harder than it looks, because R objects mutate even under read access. Every object header embeds bookkeeping for the garbage collector, and a collection writes mark bits into every reachable header. The sunlight project measured the effect after fork(): one full collection in the child privatized most of the shared pages, and a forked pool ended up far short of the memory reduction sunlight aimed for (the measurement).

Both active runtime projects draw boundaries from these object rules. threaded-r keeps a small fixed set of builtin constants, R_NilValue among them, in an immortal arena. No collector marks or relinks those objects, so interpreters can share them, analogous to CPython PEP 683 immortal objects. rrs gives each interpreter its own heap, garbage collector, and string cache, so no object graph ever spans two interpreters.

When two interpreters exchange a data frame, which nodes of its object graph can they share by pointer, and which must they copy?

Further reading

Where this appears

  • threaded-r What counts as one object decides which values can cross an interpreter boundary without a copy.
  • r-in-rust (rrs) rrs must reproduce typeof(), class(), attributes, and copy-on-modify behavior exactly.

Where to go next

Back to top