Data Structure: Matrix

Full Screen

A list of some common functions in R for creating, manipulating, and analyzing matrix objects:

1. Creating Matrices

  • matrix() – Create a matrix by specifying the number of rows and columns.
  • cbind() – Combine vectors or matrices by columns.
  • rbind() – Combine vectors or matrices by rows.
  • diag() – Create a diagonal matrix or extract diagonal elements from a matrix.

2. Accessing and Modifying Matrices

  • dim() – Get or set the dimensions of a matrix.
  • nrow() – Get the number of rows in a matrix.
  • ncol() – Get the number of columns in a matrix.
  • [] – Subset elements, rows, or columns of a matrix.
  • colnames() / rownames() – Set or retrieve column and row names.

3. Matrix Operations

  • %*% – Matrix multiplication.
  • t() – Transpose of a matrix.
  • solve() – Find the inverse of a matrix.
  • det() – Calculate the determinant of a matrix.
  • crossprod() – Compute the cross-product of two matrices (equivalent to t(A) %*% B).
  • tcrossprod() – Compute the cross-product in reverse (equivalent to A %*% t(B)).

4. Element-wise Operations

  • +, -, *, / – Element-wise addition, subtraction, multiplication, and division.
  • ^ – Element-wise exponentiation.

5. Matrix Decomposition

  • eigen() – Calculate eigenvalues and eigenvectors of a matrix.
  • svd() – Singular value decomposition.
  • chol() – Cholesky decomposition.

6. Row and Column Operations

  • rowSums() – Sum of each row.
  • colSums() – Sum of each column.
  • rowMeans() – Mean of each row.
  • colMeans() – Mean of each column.
  • apply() – Apply a function to rows or columns of a matrix.

7. Logical and Conditional Functions

  • any() – Check if any elements are TRUE (e.g., any(matrix > 5)).
  • all() – Check if all elements are TRUE.
  • is.na() – Check for NA values in the matrix.
  • na.omit() – Remove rows with NA values.

8. Reshaping and Converting

  • as.matrix() – Convert an object to a matrix.
  • as.vector() – Convert a matrix to a vector.
  • dimnames() – Set or retrieve row and column names.
  • t() – Transpose a matrix.

9. Other Useful Functions

  • which() – Get the indices of elements that meet a condition.
  • which.max() / which.min() – Find the index of the maximum or minimum element.
  • diag() – Extract or create a diagonal of a matrix.
  • outer() – Compute the outer product of two vectors to form a matrix.

These functions are commonly used when working with matrices in R, covering a range of matrix operations from basic creation and manipulation to advanced computations and analysis.