5.2 Accessing Elements

Just as for vectors, elements of a matrix are accessed with the [] operator, but each element is specified by two indices: one for the row and one for the column.

> B <- matrix(1:12, ncol=4)
> B[2,3]
[1] 8

These operators can also be used to access (or slice) any subset of a matrix using index or locigal vectors. To just get the second column of the first two rows, for instance, you can use

> B[1:2,2]
[1] 4 5

Or you may want to get the second and fourth column of all but the second row:

> B[-2,c(2,4)]
     [,1] [,2]
[1,]    4   10
[2,]    6   12

Based on the slice, R will either return a matrix or a vector.

Sometimes, you may want to access an entire row or an entire column. This is readily done by leaving an index empty, which implies using the full range of possible indexes.

> B[2,]
[1]  2  5  8 11
> B[,3]
[1] 7 8 9

Just as for vectors, matrix elements can also be accesed using logical matrices (or vectors). A logical matrix can be created either with matrix()

> matrix(c(TRUE, TRUE, FALSE), nrow=3, ncol=2)
      [,1]  [,2]
[1,]  TRUE  TRUE
[2,]  TRUE  TRUE
[3,] FALSE FALSE

or using conditions such as

> matrix(1:12, nrow=3) %% 2 == 0
      [,1]  [,2]  [,3]  [,4]
[1,] FALSE  TRUE FALSE  TRUE
[2,]  TRUE FALSE  TRUE FALSE
[3,] FALSE  TRUE FALSE  TRUE

This allows us to for instance replace all odd elements with 0

> A <- matrix(1:12, nrow=3);
> A
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
> A[A %% 2 == 1] <- 0
> A
     [,1] [,2] [,3] [,4]
[1,]    0    4    0   10
[2,]    2    0    8    0
[3,]    0    6    0   12

Finally, elements of a matrix can also be accessed via the [] operator using a single index. In this case, the index is interpreted as linearized into a vector by stacking the columns.

> A <- matrix(1:12, nrow=3, byrow=FALSE)
> A
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
> A[c(5,7)]
[1] 5 7
> A <- matrix(1:12, nrow=3, byrow=TRUE)
> A
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    5    6    7    8
[3,]    9   10   11   12
> A[c(5,7)]
[1] 6 3

This then also allows us to use the function which() to assign values based on a vector of indexes that pass a given condition.

> A <- matrix(-2:2, nrow=4, ncol=5)
> which(A < 0)
[1]  1  2  6  7 11 12 16 17
> A[which(A<0)] <- 420
> A
     [,1] [,2] [,3] [,4] [,5]
[1,]  420    2    1    0  420
[2,]  420  420    2    1    0
[3,]    0  420  420    2    1
[4,]    1    0  420  420    2

5.2.1 Exercises: Accessing Matrix Elements

See Section 18.0.12 for solutions.

  1. Create a 4x4 matrix A with elements 1, 2, …, 16 filled row by row (first row is 1, 2, 3, 4). Assign a slice of all but the last row to a new matrix B.

  2. What is the sum of all elements in the second row of the matrix A from above? And of all elements of the third column?

  3. Replace all elements Aij of matrix A for which Aij+1<(Aij3)2 with value -1. tip: which(condition)