</>
Skip to content
R lessons (10/41)

R — Matrices

What is a matrix?

A matrix is a two-dimensional array where all elements are the same type:

m <- matrix(1:12, nrow = 3, ncol = 4)
print(m)
#      [,1] [,2] [,3] [,4]
# [1,]    1    4    7   10
# [2,]    2    5    8   11
# [3,]    3    6    9   12

Matrices fill column by default (by column). Use byrow = TRUE to fill row by row.

Creating matrices

# Fill by column (default)
m <- matrix(1:12, nrow = 3, ncol = 4)

# Fill by row
m <- matrix(1:12, nrow = 3, ncol = 4, byrow = TRUE)
#      [,1] [,2] [,3] [,4]
# [1,]    1    2    3    4
# [2,]    5    6    7    8
# [3,]    9   10   11   12

# From vectors
v <- c(1, 2, 3, 4, 5, 6)
m <- matrix(v, nrow = 2)

# With specific values
m <- matrix(c(1, 0, 0, 1), nrow = 2)  # identity-like

Accessing elements

m <- matrix(1:12, nrow = 3, ncol = 4)

# Single element
m[1, 2]     # 4 (row 1, column 2)

# Entire row
m[1, ]      # 1 4 7 10

# Entire column
m[, 1]      # 1 2 3

# Multiple rows/columns
m[c(1, 3), ]     # rows 1 and 3
m[, c(1, 3)]     # columns 1 and 3

# By name (if named)
rownames(m) <- c("A", "B", "C")
colnames(m) <- c("x", "y", "z", "w")
m["A", "y"]      # 4

Matrix dimensions

m <- matrix(1:12, nrow = 3, ncol = 4)

dim(m)     # 3 4 (rows, columns)
nrow(m)    # 3
ncol(m)    # 4
length(m)  # 12 (total elements)

Modifying matrices

m <- matrix(0, nrow = 3, ncol = 3)

# Change single element
m[1, 1] <- 1
m[2, 2] <- 1
m[3, 3] <- 1  # now it's an identity matrix

# Change entire row
m[1, ] <- c(1, 2, 3)

# Change entire column
m[, 3] <- c(10, 20, 30)

# Add row/column
m <- rbind(m, c(4, 5, 6))   # add row
m <- cbind(m, c(7, 8, 9, 10))  # add column

Matrix operations

A <- matrix(c(1, 2, 3, 4), nrow = 2)
B <- matrix(c(5, 6, 7, 8), nrow = 2)

# Element-wise operations
A + B       # add
A - B       # subtract
A * B       # element-wise multiply
A / B       # element-wise divide
A ^ 2       # element-wise power

# Scalar operations
A + 10      # add 10 to every element
A * 2       # multiply every element by 2

Matrix algebra

A <- matrix(c(1, 2, 3, 4), nrow = 2)
B <- matrix(c(5, 6, 7, 8), nrow = 2)

# Matrix multiplication
A %*% B

# Transpose
t(A)

# Determinant
det(A)  # -2

# Inverse
solve(A)

# Eigenvalues and eigenvectors
eigen(A)

# Matrix rank
qr(A)$rank

Row and column operations

m <- matrix(1:12, nrow = 3, ncol = 4)

# Row sums and means
rowSums(m)     # 22 26 30
rowMeans(m)    # 5.5 6.5 7.5

# Column sums and means
colSums(m)     # 6 15 24 33
colMeans(m)    # 2 5 8 11

# Apply function to rows or columns
apply(m, 1, sum)   # same as rowSums
apply(m, 2, mean)  # same as colMeans

# Apply custom function
apply(m, 1, function(x) max(x) - min(x))  # range of each row

Combining matrices

A <- matrix(1:4, nrow = 2)
B <- matrix(5:8, nrow = 2)

# Bind rows
rbind(A, B)
#      [,1] [,2]
# [1,]    1    3
# [2,]    2    4
# [3,]    5    7
# [4,]    6    8

# Bind columns
cbind(A, B)
#      [,1] [,2] [,3] [,4]
# [1,]    1    3    5    7
# [2,]    2    4    6    8

Naming rows and columns

m <- matrix(1:6, nrow = 2, ncol = 3)
rownames(m) <- c("Row1", "Row2")
colnames(m) <- c("Col1", "Col2", "Col3")

print(m)
#      Col1 Col2 Col3
# Row1    1    3    5
# Row2    2    4    6

m["Row1", "Col2"]  # 3

Matrices vs data frames

FeatureMatrixData frame
Element typeSame typeColumns can differ
PerformanceFaster for mathSlower
Use caseLinear algebraTabular data
Accessm[i, j]df[i, j] or df$col

Practical examples

Correlation matrix

data <- mtcars[, c("mpg", "hp", "wt")]
cor(data)
#           mpg        hp        wt
# mpg  1.000000 -0.776168 -0.867659
# hp  -0.776168  1.000000  0.658748
# wt  -0.867659  0.658748  1.000000

Distance matrix

x <- c(1, 2, 3, 4, 5)
dist_matrix <- dist(matrix(x, nrow = 1))

Identity matrix

diag(5)  # 5x5 identity matrix

Diagonal extraction

m <- matrix(1:9, nrow = 3)
diag(m)  # 1 5 9 — diagonal elements

Mini Practice

  1. Create a 4x4 matrix of random numbers with matrix(rnorm(16), nrow = 4)
  2. Extract the diagonal elements with diag()
  3. Compute the matrix product of two 3x3 matrices
  4. Use apply() to find the maximum value in each row
  5. Create an identity matrix and verify that A %*% diag(3) == A

Next: data frames — R's workhorse →

Related Topics

Frequently Asked Questions about Matrices

What is Matrices in R?

Matrices is a fundamental concept in R. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Matrices?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Matrices.

Why is Matrices important in R?

Matrices is essential for R development. Understanding this concept will help you write better code and solve real-world problems more effectively.