R Data Structures

Article · 2:00

Vectors, matrices, lists, data frames and factors - and the coercion rules that decide what happens when you mix types.

R has five structures you will use constantly, and they divide along two axes: one type or many, and one dimension or two.

Vectors are the foundation. A vector holds elements of exactly one type - numeric, character, logical, integer or complex. Put two types in one and R does not complain: it coerces them all to the most accommodating type, following a fixed hierarchy. logical → integer → double → character. So c(1, "a") is a character vector, and c(TRUE, 1) is numeric with TRUE becoming 1. This silent coercion is responsible for an enormous share of R bugs, and the fix is to check with str() rather than assume.

The recycling rule is the other surprise. When two vectors of different lengths meet, R repeats the shorter one to match. c(1, 2, 3, 4) + c(10, 20) gives 11 22 13 24. When the longer length is not a multiple of the shorter, you get a warning but still get a result - which is how a quiet bug ships.

Matrices are vectors with a dimension attribute: two-dimensional, one type throughout. They fill column-first by default, which surprises people coming from row-major languages. Arrays extend the same idea past two dimensions.

Lists are the escape hatch: a list can hold anything, including other lists, and its elements can have different types and lengths. Every complicated object in R is a list underneath - the result of lm() is a list, and so is a data frame.

Data frames are the structure the whole language is built around: a list of equal-length vectors, presented as a table. Each column is one type; different columns may differ. A tibble is the tidyverse's data frame with better printing and fewer surprises, and the two are interchangeable for almost everything.

Factors are how R stores categorical data: an integer vector plus a levels attribute naming the categories. They exist because statistical models need to know that "low", "medium" and "high" are categories with an order rather than three strings. They are also a notorious source of confusion, because a factor looks like text and behaves like an integer. The classic disaster is as.numeric(factor), which returns the level codes rather than the numbers you see. Since R 4.0, read.csv no longer converts strings to factors automatically, which removed most of the pain.

# ---- Vectors: one type, and R will enforce it ------------------------
nums  <- c(1, 2, 3, 4, 5)
chars <- c("ada", "grace", "alan")
bools <- c(TRUE, FALSE, TRUE)

# Coercion, silently, up this hierarchy:
#   logical  ->  integer  ->  double  ->  character
mixed <- c(1, "a", TRUE)
class(mixed)              # "character" - the 1 and the TRUE became text
str(c(TRUE, 1L, 2.5))     # num [1:3] 1 1 2.5

# This is why str() is the most useful function in R. Check, do not assume.

# ---- The recycling rule ----------------------------------------------
c(1, 2, 3, 4) + c(10, 20)      # 11 22 13 24  - the short one repeats
c(1, 2, 3)    + c(10, 20)      # 11 22 13, AND a warning. Still a result.

# ---- Sequences and repetition ----------------------------------------
1:10                     # 1 2 3 ... 10
seq(0, 1, by = 0.25)     # 0.00 0.25 0.50 0.75 1.00
seq_len(5)               # 1 2 3 4 5  - safe when the length may be 0
rep(c("a", "b"), times = 2)   # "a" "b" "a" "b"
rep(c("a", "b"), each  = 2)   # "a" "a" "b" "b"

# ---- Matrices: fill order matters ------------------------------------
m <- matrix(1:6, nrow = 2)                 # fills DOWN the columns
#      [,1] [,2] [,3]
# [1,]    1    3    5
# [2,]    2    4    6

matrix(1:6, nrow = 2, byrow = TRUE)        # fills across the rows

dim(m)          # 2 3
t(m)            # transpose
m %*% t(m)      # %*% is matrix multiplication. * is elementwise.

# ---- Lists: anything, including other lists --------------------------
person <- list(
  name   = "Ada",
  born   = 1815,
  fields = c("mathematics", "computing"),
  nested = list(a = 1, b = 2)
)

str(person)
person$name                # "Ada"
person[["fields"]][2]      # "computing"

# ---- Data frames: a list of equal-length vectors ---------------------
df <- data.frame(
  name  = c("ada", "grace", "alan"),
  born  = c(1815, 1906, 1912),
  alive = c(FALSE, FALSE, FALSE)
)

str(df)
nrow(df); ncol(df); dim(df)
names(df)        # the column names
head(df, 2)

# A data frame IS a list underneath:
is.list(df)      # TRUE

# ---- Factors: integers wearing labels --------------------------------
sizes <- factor(c("small", "large", "medium", "small"),
                levels = c("small", "medium", "large"),   # the ORDER
                ordered = TRUE)

levels(sizes)    # "small" "medium" "large"
as.integer(sizes)# 1 3 2 1  - the codes, not the labels
table(sizes)

# THE CLASSIC TRAP. A factor of numbers:
f <- factor(c(10, 20, 30))
as.numeric(f)             # 1 2 3   <- the level codes. NOT the numbers.
as.numeric(as.character(f))   # 10 20 30   <- the fix. Always via character.

Discussion

No questions on this topic yet. Sign in to ask the first one.