R Matrix Indexing
Matrix indexing selects cells with a row part and a column part. A matrix is the grid built by matrix() in the beginner course.
Pick by row and column
The first print reads the cell in row two and column one. The next prints show one full row and one full column.
m <- matrix(1:6, nrow = 2, byrow = TRUE)
print(m[2, 1])
print(m[1, ])
print(m[, 3])Keep the matrix shape
A plain row pick prints as a vector. With drop set to FALSE the same pick keeps its row and column headers.
m <- matrix(1:6, nrow = 2, byrow = TRUE)
print(m[1, ])
print(m[1, , drop = FALSE])Pick cells with a test
The test compares every cell with 4. The matching cells print as one vector.
m <- matrix(1:6, nrow = 2, byrow = TRUE)
print(m[m > 4])Replace the picked cells
The assignment writes 0 into every cell above 4. The other cells keep their values.
m <- matrix(1:6, nrow = 2, byrow = TRUE)
m[m > 4] <- 0
print(m)Read with one index
A single index counts down the first column and then down the next one. The third and fourth cells are the two cells of the second column.
m <- matrix(1:6, nrow = 2)
print(m[3])
print(m[4])Example
grid <- matrix(c(3, 9, 5, 7, 2, 8), nrow = 2, byrow = TRUE)
print(grid[2, , drop = FALSE])
print(grid[grid > 6])Key points
- The first index picks rows and the second index picks columns.
- A blank side keeps every row or every column on that side.
- drop = FALSE keeps a one-row or one-column result as a matrix.
- A logical matrix picks the cells where the test is TRUE.
- An assignment through a logical matrix replaces only the picked cells.
- One index with no comma counts down the columns in storage order.
In this example, the second row stays a matrix because drop is FALSE. The test then picks the three cells above 6 and prints them in column order as 7, 9 and 8.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does m[1, , drop = FALSE] return?