Add a data slice (i.e., n-by-n matrix) to a multidimensional matrix in R

According to the heading, is there a way to add a data slice, which is an n-by-n-matrix, to an existing N-dimensional matrix in R?

For example, I have the following:

one <- array(1, dim = c(3, 3))
two <- array(2, dim = c(3, 3))
three <- array(3, dim = c(6, 6))

What I would like to turn into a 6x6x3 matrix with which I can work, which will look like this:

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

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

[[3]]
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    3    3    3    3    3    3
[2,]    3    3    3    3    3    3
[3,]    3    3    3    3    3    3
[4,]    3    3    3    3    3    3
[5,]    3    3    3    3    3    3
[6,]    3    3    3    3    3    3

I know how to do this with my own code, so I'm more interested in whether there is an existing library function that supports this.

+3
source share
1 answer

In addition to abind, I think, you need to find out the maximum size of your matrices and create matrices supplemented by the appropriate number of NS?

padmat <- function(X,m,n) {
  Y <- matrix(NA,m,n)
  Y[1:nrow(X),1:ncol(X)] <- X
  Y
}
one <- array(1, dim = c(3, 3))
two <- array(2, dim = c(3, 3))
three <- array(3, dim = c(6, 6))

mlist <- list(one,two,three)

maxrows <- max(sapply(mlist,nrow))
maxcols <- max(sapply(mlist,ncol))

mlist2 <- lapply(mlist,padmat,m=maxrows,n=maxcols)

library(abind)
abind(mlist2,along=3)
+6
source

All Articles