Matrix Indexing and Subsetting
Access rows, columns, and elements using [row, col] notation.
Matrix Index Basics
To access elements in a matrix, use m[row, col] notation. Row and column indices start at 1 in R. The comma is required — omitting it treats the matrix as a flat vector.
m <- matrix(1:12, nrow = 3, ncol = 4)
cat('Full matrix:
')
print(m)
# Element at row 2, column 3
cat('m[2, 3] =', m[2, 3], '
')
# Element at row 1, column 4
cat('m[1, 4] =', m[1, 4], '
')Extracting a Full Row
Leave the column index blank to extract an entire row. The result is a vector (the matrix dimension is dropped). The comma must still be present.
scores <- matrix(c(88,92,75,81, 79,85,90,73, 95,78,82,88),
nrow = 3, byrow = TRUE)
rownames(scores) <- c('Alice', 'Bob', 'Carol')
colnames(scores) <- c('Math', 'Sci', 'Eng', 'Hist')
print(scores)
# Extract Alice's row
alice_scores <- scores[1, ]
cat('Alice:', alice_scores, '
')
cat('Alice mean:', mean(alice_scores), '
')All lessons in this course
- Creating Matrices with matrix()
- Matrix Indexing and Subsetting
- Matrix Arithmetic and Operations
- Transposing and Reshaping Matrices