How to Create Matrices in R
Learn how to create, manipulate, and perform operations on matrices in R.
Matrices are two-dimensional data structures in R with rows and columns. They’re essential for mathematical operations and data analysis.
Creating Matrices
Using matrix()
# Basic matrix
m <- matrix(1:6, nrow = 2, ncol = 3)
print(m)
# [,1] [,2] [,3]
# [1,] 1 3 5
# [2,] 2 4 6
# Fill by row instead of column
m <- matrix(1:6, nrow = 2, ncol = 3, byrow = TRUE)
print(m)
# [,1] [,2] [,3]
# [1,] 1 2 3
# [2,] 4 5 6
With Row and Column Names
m <- matrix(1:6, nrow = 2, ncol = 3,
dimnames = list(c("Row1", "Row2"),
c("Col1", "Col2", "Col3")))
print(m)
# Col1 Col2 Col3
# Row1 1 3 5
# Row2 2 4 6
From Vectors
# Combine vectors as rows
v1 <- c(1, 2, 3)
v2 <- c(4, 5, 6)
m <- rbind(v1, v2) # Row bind
print(m)
# Combine vectors as columns
m <- cbind(v1, v2) # Column bind
print(m)
Accessing Elements
Single Elements
m <- matrix(1:9, nrow = 3, ncol = 3)
# Single element [row, column]
print(m[1, 2]) # Row 1, Column 2
# Entire row
print(m[1, ]) # Row 1
# Entire column
print(m[, 2]) # Column 2
Multiple Elements
m <- matrix(1:9, nrow = 3, ncol = 3)
# Multiple rows
print(m[1:2, ])
# Multiple columns
print(m[, 2:3])
# Submatrix
print(m[1:2, 2:3])
# By row/column names
m <- matrix(1:9, nrow = 3,
dimnames = list(c("A", "B", "C"), c("X", "Y", "Z")))
print(m["A", "Y"])
Matrix Operations
Basic Arithmetic
m1 <- matrix(1:4, nrow = 2)
m2 <- matrix(5:8, nrow = 2)
# Element-wise operations
print(m1 + m2) # Addition
print(m1 - m2) # Subtraction
print(m1 * m2) # Element-wise multiplication
print(m1 / m2) # Element-wise division
# Scalar operations
print(m1 * 2) # Multiply all by 2
print(m1 + 10) # Add 10 to all
Matrix Multiplication
m1 <- matrix(1:4, nrow = 2) # 2x2
m2 <- matrix(1:6, nrow = 2) # 2x3
# Matrix multiplication
result <- m1 %*% m2
print(result) # 2x3 result
Transpose
m <- matrix(1:6, nrow = 2, ncol = 3)
print(m)
# [,1] [,2] [,3]
# [1,] 1 3 5
# [2,] 2 4 6
t_m <- t(m)
print(t_m)
# [,1] [,2]
# [1,] 1 2
# [2,] 3 4
# [3,] 5 6
Matrix Functions
Dimensions
m <- matrix(1:12, nrow = 3, ncol = 4)
dim(m) # Dimensions: 3 4
nrow(m) # Number of rows: 3
ncol(m) # Number of columns: 4
length(m) # Total elements: 12
Summary Statistics
m <- matrix(1:9, nrow = 3)
sum(m) # Sum of all elements
mean(m) # Mean of all elements
min(m) # Minimum
max(m) # Maximum
# By row or column
rowSums(m) # Sum of each row
colSums(m) # Sum of each column
rowMeans(m) # Mean of each row
colMeans(m) # Mean of each column
Apply Function
m <- matrix(1:9, nrow = 3)
# Apply function to rows (MARGIN = 1)
apply(m, 1, sum) # Same as rowSums
# Apply function to columns (MARGIN = 2)
apply(m, 2, mean) # Same as colMeans
# Custom function
apply(m, 1, function(x) max(x) - min(x)) # Range per row
Linear Algebra
Determinant and Inverse
m <- matrix(c(4, 2, 7, 6), nrow = 2)
# Determinant
det(m)
# Inverse
solve(m)
# Verify: m * inverse = identity
m %*% solve(m)
Solving Linear Equations
# Solve Ax = b
A <- matrix(c(3, 1, 2, 4), nrow = 2)
b <- c(5, 11)
x <- solve(A, b)
print(x)
# Verify
A %*% x # Should equal b
Eigenvalues and Eigenvectors
m <- matrix(c(4, 1, 2, 3), nrow = 2)
eigen_result <- eigen(m)
print(eigen_result$values) # Eigenvalues
print(eigen_result$vectors) # Eigenvectors
Special Matrices
# Identity matrix
diag(3)
# [,1] [,2] [,3]
# [1,] 1 0 0
# [2,] 0 1 0
# [3,] 0 0 1
# Diagonal matrix
diag(c(1, 2, 3))
# Extract diagonal
m <- matrix(1:9, nrow = 3)
diag(m) # c(1, 5, 9)
# Matrix of zeros
matrix(0, nrow = 3, ncol = 3)
# Matrix of ones
matrix(1, nrow = 2, ncol = 4)
Practical Examples
Correlation Matrix
# Create sample data
data <- matrix(rnorm(30), ncol = 3)
colnames(data) <- c("X", "Y", "Z")
# Correlation matrix
cor_matrix <- cor(data)
print(round(cor_matrix, 2))
Transformation Matrix
# 2D rotation matrix
rotate <- function(theta) {
matrix(c(cos(theta), sin(theta),
-sin(theta), cos(theta)),
nrow = 2)
}
# Rotate point (1, 0) by 90 degrees
point <- c(1, 0)
rotated <- rotate(pi/2) %*% point
print(round(rotated, 2)) # (0, 1)
Distance Matrix
# Points
points <- matrix(c(0, 0, 1, 0, 0, 1, 1, 1),
nrow = 4, byrow = TRUE)
# Euclidean distance matrix
dist(points)
Summary
- Create with
matrix(),rbind(), orcbind() - Access elements with
[row, column] %*%for matrix multiplication,*for element-wise- Use
t()for transpose,solve()for inverse apply()to apply functions across rows or columnsrowSums(),colSums(),rowMeans(),colMeans()for aggregation