Thursday, October 18, 2007

cbind, rbind, zbind

I needed to bind a couple of matrices in a three dimensional array. Surprisingly, there was no matrix equivalent of cbind/rbind, which neatly bind vectors and matrices into matrices. So I defined my own: zbind. It is slightly more general, as it binds any number of similar shaped arrays along a new dimension. Here's the code:
function (X, Y, ..., higher.dim = TRUE) 
# Binds arrays X, Y, ... of the same shape in an array
# of one higher dimension: zbind(1:10,15:25) == cbind(1:10,15:25).
# If higher.dim=FALSE the arguments are bind in the last dimension
{
    if (missing(Y)) 
        return(X)
    X = as.array(X)
    Y = as.array(Y)
    if (higher.dim) {
        dim(X) = c(dim(X), 1)
        dim(Y) = c(dim(Y), 1)
    }
    dx = dim(X)
    nx = length(dx)
    dy = dim(Y)
    ny = length(dy)
    idx = 1:(nx - 1)
    if (any(dx[idx] != dy[idx])) 
        stop("Arguments should have the same shape")
    z = c(X, Y)
    zz = array(z, c(dx[-nx], length(z)/prod(dx[-nx])))
    Recall(zz, ..., higher.dim = FALSE)
}

Labels: , , , , ,