How to Extract Values from a Matrix in R - dummies

How to Extract Values from a Matrix in R

By Andrie de Vries, Joris Meys

You can use these indices the same way you use vectors in R. You can assign and extract values, use numerical or logical indices, drop values by using a minus sign, and so forth.

How to use numeric indices in R

For example, you can extract the values in the first two rows and the last two columns with the following code:

> first.matrix[1:2, 2:3]
   [,1] [,2]
[1,]  4  7
[2,]  5  8

R returns you a matrix again. Pay attention to the indices of this new matrix — they’re not the indices of the original matrix anymore.

R gives you an easy way to extract complete rows and columns from a matrix. You simply don’t specify the other dimension. So, you get the second and third row from your first matrix like this:

> first.matrix[2:3,]
   [,1] [,2] [,3] [,4]
[1,]  2  5  8  11
[2,]  3  6  9  12

How to drop values using negative indices

You can drop values in a vector by using a negative value for the index. This little trick works perfectly well with matrices, too. So, you can get all the values except the second row and third column of first.matrix like this:

> first.matrix[-2,-3]
   [,1] [,2] [,3]
[1,]  1  4  10
[2,]  3  6  12

With matrices, a negative index always means: “Drop the complete row or column.” If you want to drop only the element at the second row and the third column, you have to treat the matrix like a vector. So, in this case, you drop the second element in the third column like this:

> nr <- nrow(first.matrix)
> id <- nr*2+2
> first.matrix[-id]
 [1] 1 2 3 4 5 6 7 9 10 11 12

This returns a vector, because the 11 remaining elements don’t fit into a matrix anymore. Now what happened here exactly? Remember that matrices are read column-wise. To get the second element in the third column, you need to do the following:

  1. Count the number of rows, using nrow(), and store that in a variable — for example nr.

    You don’t have to do this, but it makes the code easier to read.

  2. Count two columns and then add 2 to get the second element in the third column.

    Again store this result in a variable (for example, id).

  3. Use the one-dimensional vector extraction [] to drop this value.

You can do this in one line, like this:

> first.matrix[-(2 * nrow(first.matrix) + 2)]
 [1] 1 2 3 4 5 6 7 9 10 11 12

This is just one example of how you can work with indices while treating a matrix like a vector. It requires a bit of thinking at first, but tricks like these can offer very neat solutions to more complex problems as well, especially if you need your code to run as fast as possible.