Section 9 Matrix Subsetting

9.1 Subset a matrix

Example matrix:

x <- matrix(c(1:12), nrow=4, ncol=3)

dimnames(x) <- list(letters[1:4],LETTERS[1:3])

Index Explanation Example.
[i,j] Single square bracket with apprpriate index for the row(s) and column(s) x[1:2,2]
Positive integer Select all elements corresponding to the integer value of the specific dimension x[2,]
Negative integer Remove the elements corresponding to the integer value of the specific dimension x[-2,]; x[,-2]
Zero Select no element x[0]
Blank Select all elements for the specific dimension x[2,]; x[,2]
Logical values Select the element corresponding to the logical value TRUE x[c(T,F),]
Names Select the element corresponding to the named value x['a',]; x['a','B']

9.2 Example

x <- matrix(c(1:12), nrow=4, ncol=3)
dimnames(x) <- list(letters[1:4],LETTERS[1:3])
x

x[1:2,2]
x[2,]
x[-2,]; x[,-2]
x[0]
x[2,]; x[,2]
x[c(T,F),]
x['a',]; x['a','B']


x[2,]
x[2,3]
x[2:3,]
x[2:3,3]
x[c(1,3),]
x[c(1,3),2]
x[c(1:2,4),2]
x[c(1:2,4),c(1,3)]


x[-2,]
x[,-2]
x[-2,3]
x[1:3,-2]
x[-2,c(1,3)]
x[c(1:2,4),-2]
x[-c(1,3),1:3]


x[0]

x[]

x[,2]
x[,2, drop=FALSE]

x[c(T,F),]
x[c(T,F),c(T,F)]

x['a',]
x['a','B']
x['a',c('B','C')]
x[1:2,c('B','C')]
x[-2,c('B','C')]

x[c(-2,3),]  # Error
x[c(-2,0),]

x[x[,'A']>2, ]
x[,x['a',]>2]

Note:

  • Only 0’s may be mixed with negative subscripts

  • Be careful of R’s automatic dropping of dimensions.

  • This behavior can be turned off by setting drop = FALSE.

  • By default, when a single element of a matrix is retrieved, it is returned as a vector of length 1 rather than a 1x1 matrix.