Subset of the matrix and get NA if the index is invalid

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

For example, a matrix is ​​a subset of a<-matrix(1:15,3,5) , usually when I multiply it with 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 
+5
source share
2 answers

When selecting all of your 0 to NA , as well as any "out of range" 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 work even with combinations of missing parts:

 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 
+4
source

You can create your own fill function to fill the gap with less than 3x3 NA values

 padmatrix <- function(a, dim=c(3,3)) { stopifnot(all(dim(a)<=dim)) cbind(rep(NA,dim[2]-ncol(a)), rbind(rep(NA,dim[1]-nrow(a)), a)) } padmatrix(a[1:2, 1:2]) # [,1] [,2] [,3] # [1,] NA NA NA # [2,] NA 1 4 # [3,] NA 2 5 
+1
source

Source: https://habr.com/ru/post/1202395/


All Articles