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
Force all your 0
's to NA
s 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With