Matrices in R

R BasicsMatricesFree Lesson

Advertisement

Introduction

Matrices are two-dimensional collections of elements of the same type. They are fundamental for numerical computations.

Creating Matrices

# Using matrix() function
mat <- matrix(1:9, nrow = 3, ncol = 3)
mat

# By row
mat <- matrix(1:9, nrow = 3, ncol = 3, byrow = TRUE)
mat

# Using cbind and rbind
col1 <- c(1, 2, 3)
col2 <- c(4, 5, 6)
mat <- cbind(col1, col2)

row1 <- c(1, 2)
row2 <- c(3, 4)
mat <- rbind(row1, row2)

Matrix Operations

mat1 <- matrix(1:4, nrow = 2)
mat2 <- matrix(5:8, nrow = 2)

mat1 + mat2      # Addition
mat1 - mat2      # Subtraction
mat1 * mat2      # Element-wise multiplication
mat1 %*% mat2    # Matrix multiplication

# Scalar operations
mat1 * 2
mat1 + 10

Matrix Functions

mat <- matrix(1:9, nrow = 3)

nrow(mat)        # Number of rows
ncol(mat)        # Number of columns
dim(mat)         # Dimensions
t(mat)           # Transpose
diag(mat)       # Diagonal elements
det(mat)         # Determinant (if square)
solve(mat)       # Inverse (if invertible)

Indexing Matrices

mat <- matrix(1:9, nrow = 3)

mat[1, 1]        # Single element
mat[1, ]         # First row
mat[, 1]         # First column
mat[1:2, 1:2]    # Submatrix
mat[-1, ]        # All except first row

Matrix Properties

mat <- matrix(1:4, nrow = 2)

is.matrix(mat)   # Check if matrix
as.vector(mat)  # Convert to vector

Summary

Matrices are essential for linear algebra operations in R. They form the basis for many statistical computations.

Advertisement

Need Expert R Programming Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement