## 1.3 Subsetting a matrix

To subset a matrix, we use [ ]:

A=matrix(1:9, 3, 3) #3 rows, 3 columns
#get the first and second rows of A
#it's a 2x3 matrix
A[1:2,]
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
#get the top 2 rows and left 2 columns
A[1:2,1:2]
     [,1] [,2]
[1,]    1    4
[2,]    2    5
#What does this do?
A[c(1,3),c(1,3)]
     [,1] [,2]
[1,]    1    7
[2,]    3    9
#This?
A[c(1,2,1),c(2,3)]
     [,1] [,2]
[1,]    4    7
[2,]    5    8
[3,]    4    7

If you have used matlab, you know you can say something like A[1,end] to denote the element of a matrix in row 1 and the last column. R does not have end’. To do, the same in R you do something like:

A=matrix(1:9, 3, 3)
A[1,ncol(A)]
[1] 7
#or
A[1,dim(A)[2]]
[1] 7

Warning R will create vectors from subsetting matrices!

One of the really bad things that R does with matrices is create a vector if you happen to subset a matrix to create a matrix with 1 row or 1 column. Look at this:

A=matrix(1:9, 3, 3)
#take the first 2 rows
B=A[1:2,]
#everything is ok
dim(B)
[1] 2 3
class(B)
[1] "matrix" "array" 
#take the first row
B=A[1,]
#oh no! It should be a 1x3 matrix but it is not.
dim(B)
NULL
#It is not even a matrix any more
class(B)
[1] "integer"
#and what happens if we take the transpose?
#Oh no, it's a 1x3 matrix not a 3x1 (transpose of 1x3)
t(B)
     [,1] [,2] [,3]
[1,]    1    4    7
#A%*%B should fail because A is (3x3) and B is (1x3)
A%*%B
     [,1]
[1,]   66
[2,]   78
[3,]   90
#It works? That is horrible!

This will create hard to find bugs in your code because you will look at B=A[1,] and everything looks fine. Why is R saying it is not a matrix! To stop R from doing this use drop=FALSE.

B=A[1,,drop=FALSE]
#Now it is a matrix as it should be
dim(B)
[1] 1 3
class(B)
[1] "matrix" "array" 
#this fails as it should (alerting you to a problem!)
try(A%*%B)
Error in A %*% B : non-conformable arguments`