Intermediate

Data Structures

Master R's core data structures: vectors, matrices, arrays, lists, data frames, and factors - and know when to use each.

Vectors

Vectors are the most basic data structure in R. All elements must be the same type.

R
# Numeric vector
nums <- c(10, 20, 30, 40, 50)

# Character vector
colors <- c("red", "green", "blue")

# Logical vector
flags <- c(TRUE, FALSE, TRUE, TRUE)

# Named vector
ages <- c(Alice = 25, Bob = 30, Charlie = 35)
ages["Bob"]  # 30

# Vector operations
length(nums)    # 5
sort(nums, decreasing = TRUE)
rev(nums)       # Reverse
unique(c(1,1,2,3))  # 1 2 3

Matrices

A matrix is a 2D structure where all elements are the same type.

R
# Create a 3x4 matrix
mat <- matrix(1:12, nrow = 3, ncol = 4)
#      [,1] [,2] [,3] [,4]
# [1,]    1    4    7   10
# [2,]    2    5    8   11
# [3,]    3    6    9   12

# Fill by row instead of column
mat2 <- matrix(1:12, nrow = 3, byrow = TRUE)

# Access elements
mat[1, 2]     # Row 1, Col 2 = 4
mat[1, ]      # Entire row 1
mat[, 2]      # Entire column 2

# Matrix operations
dim(mat)       # 3 4
nrow(mat)      # 3
ncol(mat)      # 4
t(mat)         # Transpose
mat * 2        # Element-wise multiplication
mat %*% t(mat) # Matrix multiplication

Arrays

Arrays extend matrices to more than 2 dimensions:

R
# 3D array: 2 rows, 3 cols, 2 "layers"
arr <- array(1:12, dim = c(2, 3, 2))
arr[1, 2, 1]  # Row 1, Col 2, Layer 1

Lists

Lists can hold elements of different types and sizes - they are R's most flexible data structure.

R
# Named list
person <- list(
  name = "Alice",
  age = 30,
  scores = c(95, 87, 92),
  active = TRUE
)

# Access elements
person$name         # "Alice"
person[["age"]]     # 30
person[[3]]         # c(95, 87, 92)

# Nested list
company <- list(
  name = "Acme Corp",
  employees = list(
    list(name = "Alice", role = "Engineer"),
    list(name = "Bob", role = "Designer")
  )
)
company$employees[[1]]$name  # "Alice"

# Modify a list
person$email <- "alice@example.com"  # Add element
person$age <- 31                    # Update element

Data Frames

Data frames are the workhorse of R data analysis - like a spreadsheet or SQL table.

R
# Create a data frame
df <- data.frame(
  name = c("Alice", "Bob", "Charlie"),
  age = c(25, 30, 35),
  salary = c(50000, 60000, 70000),
  stringsAsFactors = FALSE
)

# Access columns
df$name          # "Alice" "Bob" "Charlie"
df[, "age"]      # 25 30 35
df[1, ]          # First row

# Filter rows
df[df$age > 28, ]   # Rows where age > 28

# Add a column
df$bonus <- df$salary * 0.1

# Summary
str(df)       # Structure
summary(df)   # Statistical summary
nrow(df)      # 3
ncol(df)      # 4
head(df, 2)  # First 2 rows

Factors

Factors represent categorical data with a fixed set of possible values (levels).

R
# Create a factor
sizes <- factor(c("S", "M", "L", "M", "S", "XL"))
levels(sizes)  # "L"  "M"  "S"  "XL" (alphabetical by default)

# Ordered factor
sizes_ord <- factor(
  c("S", "M", "L", "M", "S"),
  levels = c("S", "M", "L", "XL"),
  ordered = TRUE
)
sizes_ord[1] < sizes_ord[2]  # TRUE (S < M)

# Table of counts
table(sizes)
#  L  M  S XL
#  1  2  2  1

Which Structure to Use?

StructureDimensionsTypesUse Case
Vector1DSameSimple sequences of values
Matrix2DSameMathematical operations, linear algebra
ArraynDSameMulti-dimensional numeric data
List1DMixedComplex, heterogeneous data
Data Frame2DMixed columnsTabular data (most common for analysis)
Factor1DCategoricalCategories with fixed levels
Key takeaway: For most data analysis, you will primarily work with data frames (or tibbles in the tidyverse). Lists are essential for storing complex results, and vectors are the building blocks of everything.

Ready to Go Deeper?

Live instructor-led courses from our partners. Affiliate disclosure.