Matrices

Matrices are vectors structured by dimensions.

Contents

  1. Matrices
    1. Usage


Usage

A matrix is instantiated like:

> my.matrix <- matrix(c(1, 2, 3, 4), nrow=2, ncol=2)

Note that instantiating a vector is almost always a necessary first step for instantiating a matrix. If the data is already available as a vector, try:

> my.data <- c(1,2,3,4)
> dim(my.data) <- (2,2)

If an insufficient number of values are given, the matrix is padded out by recycling values. This does mean that a matrix populated with a single value can be instantiated like:

> all.zero <- matrix(0, 2, 2)

To append a row (or to combine two vectors into a new matrix), try:

> my.matrix <- rbind(my.matrix, c(8, 9))

To append a column, try:

> my.matrix <- cbind(my.matrix, c(10, 10, 10))

To access the dimensions of a data frame, try the dim function.

To set names for rows or columns, use the rownames and colnames functions.

Matrices are indexed in the exact same manner as vectors, except that a pair (row then column) is required.

> top.left <- my.matrix[1,1]

To select an entire row or column, try:

> my.row <- my.matrix[1,]
> my.col <- my.matrix[,1]

The diag function is heavily overloaded with meaning.

> my.vector <- diag(my.matrix)  # returns the diagonal of the matrix
> i3 <- diag(3)                 # returns the 3x3 identity matrix
> diag(i3) <- my.vector         # overwrites the diagonal of the matrix

Lastly, note these functions and operators for math:


CategoryRicottone

R/Matrices (last edited 2026-07-19 18:28:52 by DominicRicottone)