Add data slice (i.e. n-by-n matrix) to multidimensional matrix in R
As per the title开发者_StackOverflow, is there a way to append 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))
Which I would then like to have transformed into a 6x6x3 matrix that I can work with, which would look like the following:
[[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 via my own code, so I'm more interested in if there is an existing library function that supports this.
In addition to abind
, I guess you need to figure out the maximum size of your matrices and create matrices padded with the appropriate number of NAs?
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)
精彩评论