R Matrix Operations
Matrix operations go beyond simple indexing. R supports mathematical matrix operations used in linear algebra, statistics, and machine learning — all with clean, concise syntax.
Element-wise vs Matrix Multiplication
A <- matrix(c(1,2,3,4), nrow=2) B <- matrix(c(5,6,7,8), nrow=2) # Element-wise (each position multiplied independently) A * B # [,1] [,2] # [1,] 5 21 # [2,] 12 32 # True matrix multiplication (dot product) A %*% B # [,1] [,2] # [1,] 23 31 # [2,] 34 46
Matrix multiplication diagram (A %*% B):
A: [1 3] B: [5 7]
[2 4] [6 8]
Result[1,1] = 1×5 + 3×6 = 23
Result[1,2] = 1×7 + 3×8 = 31
Result[2,1] = 2×5 + 4×6 = 34
Result[2,2] = 2×7 + 4×8 = 46
Transpose
M <- matrix(c(1,2,3,4,5,6), nrow=2) # [,1] [,2] [,3] # [1,] 1 3 5 # [2,] 2 4 6 t(M) # [,1] [,2] # [1,] 1 2 # [2,] 3 4 # [3,] 5 6
Determinant and Inverse
M <- matrix(c(4, 3, 3, 2), nrow=2) det(M) # -1 (determinant) solve(M) # inverse matrix # Verify: M %*% solve(M) should give identity matrix round(M %*% solve(M)) # [,1] [,2] # [1,] 1 0 # [2,] 0 1
Solving a System of Linear Equations
# 2x + y = 5 # x + 3y = 10 A <- matrix(c(2, 1, 1, 3), nrow=2) b <- c(5, 10) solve(A, b) # x=1, y=3
Adding Rows and Columns
m1 <- matrix(1:4, nrow=2) m2 <- matrix(5:8, nrow=2) rbind(m1, m2) # stack m2 below m1 (add rows) cbind(m1, m2) # place m2 right of m1 (add columns) # Add a row of totals col_totals <- colSums(m1) rbind(m1, col_totals)
Apply Functions Across Rows or Columns
scores <- matrix(c(85,92,78,90,76,88,95,70,82), nrow=3)
rownames(scores) <- c("Student1","Student2","Student3")
colnames(scores) <- c("Math","Science","English")
# Row means (each student's average)
apply(scores, 1, mean)
# Student1 Student2 Student3
# 85.00 84.67 85.00
# Column means (each subject's average)
apply(scores, 2, mean)
# Math Science English
# 85.33 83.33 85.00
Eigenvalues and Eigenvectors
M <- matrix(c(4,1,2,3), nrow=2) eig <- eigen(M) eig$values # eigenvalues: 5 2 eig$vectors # eigenvectors (columns)
Correlation Matrix
# Create from a data matrix
data <- matrix(c(85,72,90,88,91,78,95,82,70,76), ncol=2)
colnames(data) <- c("Math","Science")
cor(data)
# Math Science
# Math 1.0000 0.9234
# Science 0.9234 1.0000
Practical: Portfolio Return Calculation
# 3 stocks, 4 months of returns (%)
returns <- matrix(c(2,3,1, -1,2,4, 3,1,2, 4,2,3),
nrow=4, byrow=TRUE)
colnames(returns) <- c("StockA","StockB","StockC")
rownames(returns) <- c("Jan","Feb","Mar","Apr")
# Average monthly return per stock
apply(returns, 2, mean)
# StockA StockB StockC
# 2.0 2.0 2.5
# Total return each month
rowSums(returns)
# Jan Feb Mar Apr
# 6 5 6 9
Matrix operations are the mathematical engine behind linear regression, principal component analysis, and neural networks. Every statistical model you build in R ultimately reduces to matrix computation under the hood.
