Labs ICT
โญ Pro Login

Matrices

A vector is a row of lockers. A matrix is a grid โ€” rows and columns. Think of a spreadsheet, a table of numbers, or a chessboard. Matrices in R are just vectors with a shape attached. Every element still has to be the same type, but now you can work in two dimensions.

Creating a Matrix with matrix()

The matrix() function takes a vector and wraps it into rows and columns. You specify nrow and ncol. By default, R fills down the first column, then the second. Set byrow = TRUE to fill left to right instead.

# A 3x3 matrix filled column-wise
m1 <- matrix(1:9, nrow = 3, ncol = 3)
print(m1)

# Same numbers filled row-wise
m2 <- matrix(1:9, nrow = 3, ncol = 3, byrow = TRUE)
print(m2)
Try it Yourself โ†’

Naming Rows and Columns

Numbers for rows and columns work, but names are easier to read. Use rownames() and colnames() to assign labels. This is especially useful when your matrix represents something like a comparison table.

sales <- matrix(c(120, 140, 110, 160, 130, 150), nrow = 2, byrow = TRUE)
rownames(sales) <- c("Store A", "Store B")
colnames(sales) <- c("Mon", "Tue", "Wed")
print(sales)

# Access by name
print(sales["Store A", "Tue"])
Try it Yourself โ†’

Indexing Matrices

Use [row, column] to pick elements. Leave either side blank to grab a whole row or column. You can also slice multiple rows and columns at once with vectors.

m <- matrix(1:9, nrow = 3, byrow = TRUE)

# Single element
print(m[2, 3])

# Whole row
print(m[2, ])

# Whole column
print(m[, 3])

# Sub-matrix
print(m[1:2, 2:3])
Try it Yourself โ†’

๐Ÿงช Quick Quiz

Which function creates a matrix in R?