← Back to R Course | Chapter 7: Data Structures | Lesson 1 of 7

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:

  1. Matrices
Syntax
r
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

markup
m <- matrix(1:6, nrow = 2, ncol = 3)
print(m)

cat("Element at row 2, col 3:", m[2, 3], "\n")
print(m[1, ])
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
  1. Expecting matrix(1:6, nrow = 2) to fill by rows, when it fills by column unless you set byrow = TRUE.
  2. Forgetting the comma when indexing, such as m[2], which returns one element by position instead of a row; use m[2, ].
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.