0Pricing
R Academy · Lesson

Matrix Indexing and Subsetting

Access rows, columns, and elements using [row, col] notation.

Matrix Indexing and Subsetting is a free R Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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), '
')

Extracting a Full Column

Leave the row index blank to extract an entire column. Like row extraction, the result is a vector. The comma separating row and column positions 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')

# Extract the Math column
math_scores <- scores[, 1]
cat('Math scores:', math_scores, '
')
cat('Math mean:  ', mean(math_scores), '
')
cat('Math max:   ', max(math_scores), '
')

Subsetting Multiple Rows and Columns

Use a vector of indices to extract multiple rows or columns at once. The result is a submatrix (still a matrix, not a vector), preserving the two-dimensional structure.

m <- matrix(1:16, nrow = 4, ncol = 4)
cat('Original 4x4:
')
print(m)

# Extract rows 1,3 and columns 2,4
sub_m <- m[c(1, 3), c(2, 4)]
cat('Submatrix rows 1,3 cols 2,4:
')
print(sub_m)
cat('Class:', class(sub_m), '
')

Accessing by Row/Column Name

If a matrix has row and column names, you can index by name instead of position. This is more readable and robust to reordering rows or columns.

scores <- matrix(c(88,92,75,81, 79,85,90,73, 95,78,82,88),
                 nrow = 3, byrow = TRUE,
                 dimnames = list(
                   c('Alice', 'Bob', 'Carol'),
                   c('Math', 'Sci', 'Eng', 'Hist')
                 ))

# Access by name
cat('Bob Science:', scores['Bob', 'Sci'], '
')
cat('Carol row:
')
print(scores['Carol', ])
cat('English column:
')
print(scores[, 'Eng'])

Logical Indexing on Matrices

You can use a logical vector (or logical matrix) to select elements. When a logical vector is used in one dimension, it selects rows/columns where the value is TRUE.

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')

# Select students with mean score >= 85
row_means <- rowMeans(scores)
high_achievers <- scores[row_means >= 85, ]
cat('High achievers (mean >= 85):
')
print(high_achievers)

Negative Indexing — Excluding Rows/Cols

Prefix an index with - to exclude that row or column. This is a clean way to drop specific rows or columns without listing all the others you want to keep.

m <- matrix(1:12, nrow = 3, ncol = 4, byrow = TRUE)
cat('Original:
')
print(m)

# Drop row 2
cat('Without row 2:
')
print(m[-2, ])

# Drop columns 1 and 3
cat('Without cols 1 and 3:
')
print(m[, c(-1, -3)])

Single Element with drop = FALSE

By default, extracting a single row or column drops the dimension (returns a vector). Use drop = FALSE to keep the result as a matrix (preserving row/column structure).

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

# Default: drops to vector
row1_vector <- m[1, ]
cat('m[1,] class:', class(row1_vector), '
')  # numeric (vector)

# drop = FALSE: keeps as 1-row matrix
row1_matrix <- m[1, , drop = FALSE]
cat('m[1,,drop=FALSE] class:', class(row1_matrix), '
')
cat('Dimensions:', dim(row1_matrix), '
')

Replacing Values by Index

You can modify specific elements by combining indexing with assignment. This works for single elements, whole rows, whole columns, or submatrices.

m <- matrix(0, nrow = 4, ncol = 4)
cat('Zero matrix:
')
print(m)

# Set diagonal to 5
for (i in 1:4) m[i, i] <- 5
cat('After setting diagonal:
')
print(m)

# Replace entire row 2
m[2, ] <- c(1, 2, 3, 4)
cat('After replacing row 2:
')
print(m)

Linear (Flat) Indexing

A matrix is stored as a flat vector internally (column by column). You can access elements with a single integer index in this flat order. This is sometimes useful for bulk operations.

m <- matrix(c(10,20,30,40,50,60), nrow = 2, ncol = 3)
cat('Matrix:
')
print(m)

# Flat indices: column by column
cat('m[1] =', m[1], '(row 1, col 1)
')
cat('m[3] =', m[3], '(row 1, col 2)
')
cat('m[5] =', m[5], '(row 1, col 3)
')

# Replace flat index 4
m[4] <- 99
print(m)

Indexing Summary

Quick reference for matrix indexing in R:

  • m[r, c] — single element at row r, col c
  • m[r, ] — entire row r
  • m[, c] — entire column c
  • m[c(r1,r2), c(c1,c2)] — submatrix
  • m['name', 'name'] — access by dimname
  • m[-r, ] — exclude row r
  • m[logical_vec, ] — logical row selection
  • m[r, , drop=FALSE] — keep as matrix
m <- matrix(c(5,10,15,20,25,30), nrow = 2, ncol = 3)
cat('m[1,2] =', m[1,2], '
')
cat('m[2,]  =', m[2,], '
')
cat('m[,3]  =', m[,3], '
')
cat('m[-1,] :
'); print(m[-1, ])

Quick Check

What does m[-2, ] return for a matrix m with 3 rows?

Recap: Matrix Indexing

Great work! Key takeaways from this lesson:

  • m[r, c] uses row then column — both positions separated by comma
  • Leave one side blank (m[r, ] or m[, c]) to extract entire rows/columns
  • Negative indices exclude rows or columns
  • Logical vectors can filter rows or columns
  • Named dimensions allow indexing by name for readability
  • drop = FALSE prevents dimension loss when extracting single rows/columns
# Practical: find best student per subject
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')

for (subj in colnames(scores)) {
  best <- rownames(scores)[which.max(scores[, subj])]
  cat('Best in', subj, ':', best, '
')
}

Frequently asked questions

Is the “Matrix Indexing and Subsetting” lesson free?

Yes — the full text of “Matrix Indexing and Subsetting” is free to read here on the web, and the R Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the R Academy course, upgrade to CoddyKit PRO.

What will I learn in “Matrix Indexing and Subsetting”?

Access rows, columns, and elements using [row, col] notation. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start R Academy?

No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Matrix Indexing and Subsetting” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this R Academy lesson?

Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Creating Matrices with matrix()
  2. Matrix Indexing and Subsetting
  3. Matrix Arithmetic and Operations
  4. Transposing and Reshaping Matrices
← Back to R Academy