1.3 Subsetting a matrix
To subset a matrix, we use [ ]
:
=matrix(1:9, 3, 3) #3 rows, 3 columns
A#get the first and second rows of A
#it's a 2x3 matrix
1:2,] A[
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
#get the top 2 rows and left 2 columns
1:2,1:2] A[
[,1] [,2]
[1,] 1 4
[2,] 2 5
#What does this do?
c(1,3),c(1,3)] A[
[,1] [,2]
[1,] 1 7
[2,] 3 9
#This?
c(1,2,1),c(2,3)] A[
[,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:
=matrix(1:9, 3, 3)
A1,ncol(A)] A[
[1] 7
#or
1,dim(A)[2]] A[
[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:
=matrix(1:9, 3, 3)
A#take the first 2 rows
=A[1:2,]
B#everything is ok
dim(B)
[1] 2 3
class(B)
[1] "matrix" "array"
#take the first row
=A[1,]
B#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)
%*%B A
[,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
.
=A[1,,drop=FALSE]
B#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