Matrix in R

Essential Operations and Applications

Author

Raju Rimal

Published

December 2, 2024

Modified

March 19, 2025

Matrices are fundamental data structures in R, ideal for handling two-dimensional data. This blog will guide you through creating, manipulating, and performing various operations on matrices in R, complete with numerous examples. Whether you’re a beginner or an experienced R user, you’ll find something valuable here!


What Is a Matrix?

A matrix in R is a two-dimensional, rectangular data structure where all elements must be of the same type (numeric, character, or logical). Think of it as a collection of vectors arranged in rows and columns.


Creating Matrices in R

1. Using matrix()

The matrix() function is the simplest way to create a matrix.

set.seed(123)
# Create a numeric matrix
mat <- matrix(sample(9), nrow = 3, ncol = 3)
print(mat)
     [,1] [,2] [,3]
[1,]    3    2    7
[2,]    6    8    1
[3,]    9    5    4

2. By Combining Vectors with rbind() or cbind()

# Combine rows
row1 <- c(1, 2, 3)
row2 <- c(4, 5, 6)
mat1 <- rbind(row1, row2)
print(mat1)
     [,1] [,2] [,3]
row1    1    2    3
row2    4    5    6
# Combine columns
col1 <- c(1, 2, 3)
col2 <- c(4, 5, 6)
mat2 <- cbind(col1, col2)
print(mat2)
     col1 col2
[1,]    1    4
[2,]    2    5
[3,]    3    6

3. From a Vector with Dimensions

You can convert a vector into a matrix by setting its dimensions using dim().

vec <- 1:12
dim(vec) <- c(3, 4)
print(vec)
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12

Basic Matrix Operations

1. Accessing Elements

Use indices to access elements, rows, or columns of a matrix.

# Access an element
mat[2, 3]  # Row 2, Column 3
[1] 1
# Access a row
mat[1, ]
[1] 3 2 7
# Access a column
mat[, 2]
[1] 2 8 5

2. Matrix Arithmetic

You can perform element-wise operations directly on matrices.

mat1 <- matrix(c(2, 7, 0, 5), nrow = 2)
mat2 <- matrix(c(5, 6, 9, 4), nrow = 2)

# Element-wise addition
mat1 + mat2
     [,1] [,2]
[1,]    7    9
[2,]   13    9
# Element-wise multiplication
mat1 * mat2
     [,1] [,2]
[1,]   10    0
[2,]   42   20
# Scalar multiplication
2 * mat1
     [,1] [,2]
[1,]    4    0
[2,]   14   10

3. Matrix Multiplication

Use %*% for matrix multiplication.

result <- mat1 %*% mat2
print(result)
     [,1] [,2]
[1,]   10   18
[2,]   65   83

4. Transpose a Matrix

Transpose a matrix using the t() function.

t(mat)
     [,1] [,2] [,3]
[1,]    3    6    9
[2,]    2    8    5
[3,]    7    1    4

5. Determinant and Inverse

# Determinant
det(mat)
[1] -243
# Inverse (only for square matrices)
solve(mat)
           [,1]        [,2]        [,3]
[1,] -0.1111111 -0.11111111  0.22222222
[2,]  0.0617284  0.20987654 -0.16049383
[3,]  0.1728395 -0.01234568 -0.04938272

Matrix Functions and Operations

1. Apply Functions to Rows or Columns

Use apply() to perform operations on rows or columns.

# Sum of rows
apply(mat, 1, sum)
[1] 12 15 18
# Sum of columns
apply(mat, 2, sum)
[1] 18 15 12

2. Row and Column Binding

Add rows or columns to an existing matrix.

# Add a row
mat <- rbind(mat, c(10, 11, 12))

# Add a column
mat <- cbind(mat, c(13, 14, 15))
Warning in cbind(mat, c(13, 14, 15)): number of rows of result is not a
multiple of vector length (arg 2)

3. Matrix Dimensions

# Number of rows and columns
nrow(mat)
[1] 4
ncol(mat)
[1] 4
# Dimensions
dim(mat)
[1] 4 4

4. Extract Diagonals

diag(mat)
[1]  3  8  4 13

5. Identity Matrix

Create an identity matrix with diag().

diag(1, 3, 3)  # 3x3 identity matrix
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1

Special Matrices

1. Zero Matrix

matrix(0, nrow = 3, ncol = 3)
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    0    0
[3,]    0    0    0

2. Diagonal Matrix

diag(c(1, 2, 3))
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    2    0
[3,]    0    0    3

3. Random Matrix

Generate matrices with random numbers.

matrix(runif(9), nrow = 3)  # Uniform distribution
          [,1]      [,2]       [,3]
[1,] 0.4533342 0.1029247 0.04205953
[2,] 0.6775706 0.8998250 0.32792072
[3,] 0.5726334 0.2460877 0.95450365
matrix(rnorm(9), nrow = 3)  # Normal distribution
          [,1]       [,2]       [,3]
[1,] 1.2240818  0.1106827  0.4978505
[2,] 0.3598138 -0.5558411 -1.9666172
[3,] 0.4007715  1.7869131  0.7013559

Advanced Matrix Operations

1. Eigenvalues and Eigenvectors

eigen(mat)
eigen() decomposition
$values
[1] 35.473352 -6.541417 -5.178552  4.246617

$vectors
          [,1]       [,2]        [,3]        [,4]
[1,] 0.3914594 -0.6682313 -0.83892483  0.48333070
[2,] 0.4333322 -0.3286765 -0.16776284 -0.80395643
[3,] 0.4894401 -0.1857571  0.07737131  0.34609112
[4,] 0.6476350  0.6410405  0.51193207 -0.01632281

2. Singular Value Decomposition (SVD)

svd(mat)
$d
[1] 36.039191  8.057178  6.073354  2.893603

$u
           [,1]        [,2]         [,3]        [,4]
[1,] -0.3945895 -0.09791418 -0.861480899 -0.30424099
[2,] -0.4543558 -0.53481886  0.460781405 -0.54333236
[3,] -0.5065236 -0.36518921 -0.002329039  0.78106676
[4,] -0.6174899  0.75565762  0.213367602 -0.04649824

$v
           [,1]        [,2]       [,3]       [,4]
[1,] -0.4063220  0.09522161  0.3775443  0.8266170
[2,] -0.3815022  0.24970384  0.7077947 -0.5395653
[3,] -0.3510749  0.79269889 -0.4970054 -0.0368852
[4,] -0.7523994 -0.54791360 -0.3308664 -0.1556059

3. Cross Product and Outer Product

# Cross product
crossprod(mat)
     [,1] [,2] [,3] [,4]
[1,]  226  209  183  388
[2,]  209  214  174  356
[3,]  183  174  210  321
[4,]  388  356  321  759
# Outer product
outer(c(1, 2), c(3, 4))
     [,1] [,2]
[1,]    3    4
[2,]    6    8

4. Matrix Reshaping

Reshape matrices using array().

array(1:12, dim = c(3, 2, 2))
, , 1

     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

, , 2

     [,1] [,2]
[1,]    7   10
[2,]    8   11
[3,]    9   12

Practical Applications of Matrices in R

1. Solving Linear Systems

Solve Ax = b using solve().

A <- matrix(c(2, 1, 1, 3), nrow = 2)
b <- c(5, 10)
x <- solve(A, b)
print(x)
[1] 1 3

2. Data Representation

Matrices are widely used to store and manipulate datasets in statistics and machine learning.


Best Practices for Using Matrices

  1. Use Descriptive Names: Name matrices and their dimensions clearly.
  2. Choose the Right Data Type: Ensure all elements in the matrix are of the same type.
  3. Understand Alternatives: For heterogeneous data, consider data.frame or tibble.

Conclusion

Matrices are versatile and essential in R for numerical computations and data handling. From basic operations to advanced applications, mastering matrices opens the door to solving complex problems effectively. Practice with the examples above and experiment to deepen your understanding of this powerful R data structure!