Matrices: Matrices in R
Selection of components and assignment of values
Selection of components and submatrices You can select components of arrays in various ways. We give a few examples showing that indexing starts at (1, 1) and that there are smart ways to create submatrices. The last command in the session below illustrates that you can consider a matrix in R as a column vector obtained by stacking vertically all the columns from left to right; you can therefore designate a single element with one index.
> M <- matrix(2:13, nrow=3, byrow=TRUE); M
[,1] [,2] [,3] [,4]
[1,] 2 3 4 5
[2,] 6 7 8 9
[3,] 10 11 12 13
> M[2,3] # a single element
[1] 8
> M[,3] # third column
[1] 4 8 12
> M[1,] # first row
[1] 2 3 4 5
> M[1,2:4] # first row, all except first column
[1] 3 4 5
> M[1:2,1:2] # submatrix
[,1] [,2]
[1,] 2 3
[2,] 6 7
> M[6] # selection of component by considering matrix as column vector
[1] 11
Selection via logical expressions You can also use logical indexing (with zeros and ones) to select matrix elements. You need relational operators for this, such as the ones in the table below. Besides logical indexing you can also use the which
instruction to find suitable indices for a logical expression.
== | equal to | ~= | not equal to |
< | less than | > | greater than |
<= | less than or equal to | >= | greater than or equal to |
> M <- matrix(2:13, nrow=3, byrow=TRUE); M
[,1] [,2] [,3] [,4]
[1,] 2 3 4 5
[2,] 6 7 8 9
[3,] 10 11 12 13
> M>7 # matrix entries TRUE if the condition is met, FALSE otherwise
[,1] [,2] [,3] [,4]
[1,] FALSE FALSE FALSE FALSE
[2,] FALSE FALSE TRUE TRUE
[3,] TRUE TRUE TRUE TRUE
> M[M>7] # selection of components
[1] 10 11 8 12 9 13
> which(M<8) # selection of indices (columnwise) via which command
[1] 1 2 4 5 7 10
> M[.Last.value] # columnwise selection of components
[1] 2 6 3 7 4 5
Assignment Components to which you refer can also be assigned new values.
> M[3,4] <- 17; M [,1] [,2] [,3] [,4] [1,] 2 3 4 5 [2,] 6 7 8 9 [3,] 10 11 12 17 > M[,4] <- 1; M # change of one matrix entry [,1] [,2] [,3] [,4] [1,] 2 3 4 1 [2,] 6 7 8 1 [3,] 10 11 12 1 > M[,4] <- 1; M # assign all entries in fourth column the value 1 [,1] [,2] [,3] [,4] [1,] 2 3 4 1 [2,] 6 7 8 1 [3,] 10 11 12 1 > M <- M[-1,]; M # remove the first row [,1] [,2] [,3] [,4] [1,] 6 7 8 9 [2,] 10 11 12 13 > M[,] <- 0; M # assign all matrix entries the value 0 [,1] [,2] [,3] [,4] [1,] 0 0 0 0 [2,] 0 0 0 0
Change of shape You can change the shape from a vector or matrix. The following two examples illustrate this.
> v <- 1:6; v # vector of length 6
[1] 1 2 3 4 5 6
> A <- matrix(v, nrow=3); A # 3x2 matrix
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
> B <- matrix(A, nrow=2); B # 2x3 matrix
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
> t(B) # transpose of matrix B
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6