Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subset a matrix, and get NA if index is not valid

Tags:

r

matrix

subset

I am trying to subset a matrix to always get a 3*3 matrix.

For example, the matrix being subset is a<-matrix(1:15,3,5), usually when I subset it using a[0:2,0:2], I get:

      [,1] [,2]
[1,]    1    4
[2,]    2    5

But I want to get something like:

      [,1] [,2] [,3]
[1,]   NA    NA   NA
[2,]   NA    1    4
[3,]   NA    2    5
like image 266
ttliker Avatar asked Sep 12 '14 02:09

ttliker


1 Answers

Force all your 0's to NAs when you select, as well as any 'out-of-bounds' values:

ro <- 0:2
co <- 0:2
a[replace(ro,ro == 0 | ro > nrow(a),NA),
  replace(co,co == 0 | co > ncol(a),NA)]

#     [,1] [,2] [,3]
#[1,]   NA   NA   NA
#[2,]   NA    1    4
#[3,]   NA    2    5

This will even work with combinations of the parts you want missing:

ro <- c(1,0,2)
co <- 0:2
a[replace(ro,ro == 0 | ro > nrow(a),NA),
  replace(co,co == 0 | co > ncol(a),NA)]

#     [,1] [,2] [,3]
#[1,]   NA    1    4
#[2,]   NA   NA   NA
#[3,]   NA    2    5
like image 93
thelatemail Avatar answered Sep 18 '22 09:09

thelatemail