Manipulating Matrices

Accessing Matrix Elements

As with vectors, we can access and assign values within a matrix using the square brackets operator, [], but with one key difference: matrices require two indices, one to define the row selection and one to define the column selection.

(m1 <- matrix(1:12, 3, 4))
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
# Select the first two rows and the first three columns, then print the selected
# elements as a matrix
m1[1:2, 1:3]
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
# Select the first and third rows and second and third column, then save the
# selection as a new matrix called `m2`
(m2 <- m1[c(1, 3), 2:3])
     [,1] [,2]
[1,]    4    7
[2,]    6    9

Modifying Matrix Elements

Editing the value of matrix elements works the same way it did for vectors. We , use the [] operator to select the values we want to overwrite, and assign new values for the selected elements using the ordinary assignment operator, <-.

(m3 <- matrix(1, 3, 3))
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
[3,]    1    1    1
# Replace the element in the first row and second column with 33
m3[1, 2] <- 33
m3
     [,1] [,2] [,3]
[1,]    1   33    1
[2,]    1    1    1
[3,]    1    1    1
# Replace all elements in the range covered by the second and third rows and the
# first and third columns with 44 
m3[2:3, c(1, 3)] <- 44
m3
     [,1] [,2] [,3]
[1,]    1   33    1
[2,]   44    1   44
[3,]   44    1   44
Back to top