Matrices in R
A matrix is a two-dimensional data structure in R, where all elements are of the same type (numeric, character, or logical). Matrices are useful for mathematical operations, data analysis, and visualizations. In R, matrices are created using the matrix()
function.
Key Features of Matrices
- Dimensions: Matrices have rows and columns. For example, a 3×4 matrix has 3 rows and 4 columns.
- Homogeneous Data: All elements must be of the same type.
- Indexing: Elements are accessed using row and column indices, e.g.,
matrix_name[row, column]
.
Example: Creating a 2×3 matrix of numbers 1 to 6:
my_matrix <- matrix(1:6, nrow = 2, ncol = 3)
print(my_matrix)
Output:
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
Exercise
Create a 3×3 matrix with values 9, 8, 7, 6, 5, 4, 3, 2, 1. Print the matrix.
Answer and Solution
my_matrix <- matrix(c(9, 8, 7, 6, 5, 4, 3, 2, 1), nrow = 3, byrow = TRUE)
print(my_matrix)
Output:
[,1] [,2] [,3]
[1,] 9 8 7
[2,] 6 5 4
[3,] 3 2 1
Creating Matrices from Scratch
Matrices can be created using vectors and the matrix()
function. You can specify the number of rows (nrow
) and columns (ncol
).
Syntax
matrix(data = vector, nrow = number_of_rows, ncol = number_of_columns, byrow = FALSE)
Example: Create a matrix from a vector:
vec <- c(10, 20, 30, 40, 50, 60)
mat <- matrix(vec, nrow = 2, ncol = 3)
print(mat)
Output:
[,1] [,2] [,3]
[1,] 10 30 50
[2,] 20 40 60
Exercise
Create a 2×4 matrix with values 1, 2, 3, 4, 5, 6, 7, 8. Fill the matrix column-wise.
Answer and Solution
mat <- matrix(1:8, nrow = 2, ncol = 4)
print(mat)
Output:
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8
Performing Matrix Operations and Algebra
R supports matrix operations like addition, subtraction, multiplication, and division. Use %*%
for matrix multiplication.
Example: Matrix Addition
mat1 <- matrix(1:4, nrow = 2)
mat2 <- matrix(5:8, nrow = 2)
result <- mat1 + mat2
print(result)
Output:
[,1] [,2]
[1,] 6 10
[2,] 8 12
Exercise
Multiply the following matrices:
A <- matrix(c(1, 2, 3, 4), nrow = 2)
B <- matrix(c(5, 6, 7, 8), nrow = 2)
Answer and Solution
result <- A %*% B
print(result)
Output:
[,1] [,2]
[1,] 19 22
[2,] 43 50
Indexing and Subsetting Matrices
You can access specific elements, rows, or columns using indices. R uses 1-based indexing.
Example: Access the second row of a matrix
mat <- matrix(1:9, nrow = 3)
second_row <- mat[2, ]
print(second_row)
Output:
[1] 4 5 6
Exercise
Extract the element in the 3rd row and 2nd column of the matrix:
mat <- matrix(1:9, nrow = 3)
Answer and Solution
element <- mat[3, 2]
print(element)
Output:
[1] 8
Using Built-in Matrix Functions
R provides functions like t()
for transpose, det()
for determinant, and solve()
for inverse.
Example: Transpose a Matrix
mat <- matrix(1:6, nrow = 2)
transpose <- t(mat)
print(transpose)
Output:
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
Exercise
Find the determinant of the matrix:
mat <- matrix(c(1, 2, 3, 4), nrow = 2)
Answer and Solution
det_value <- det(mat)
print(det_value)
Output:
[1] -2