Matrices
A matrix is a grid of rows and columns of the same kind of value, like a tray of muffins or a chessboard. You find a value by its row and column.
In this page:
Syntax
matrix_name <- matrix(data, nrow = rows, ncol = cols)
matrix_name[row, col]
Matrices
A matrix is a two-dimensional collection of values of a single type, created with matrix(data, nrow, ncol).
Elements are accessed with m[row, col], and an entire row or column can be selected by leaving the other index blank, like m[1, ]. Matrices support standard linear algebra operations like matrix multiplication with %*%.
Note:
m[1, ] selects the entire first row; m[, 1] selects the entire first column.
Example: Matrices
m <- matrix(1:6, nrow = 2, ncol = 3)
print(m)
cat("Element at row 2, col 3:", m[2, 3], "\n")
print(m[1, ])
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Expecting
matrix(1:6, nrow = 2)to fill by rows, when it fills by column unless you setbyrow = TRUE. - Forgetting the comma when indexing, such as
m[2], which returns one element by position instead of a row; usem[2, ]. - Supplying data whose length does not fit the dimensions, which recycles the values with only a warning.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: