Effectively “apply” to an array and maintain structure

I have an array of matrices.

dims <- c(10000,5,5)
mat_array <- array(rnorm(prod(dims)), dims)

I would like to perform a matrix operation (for example, inversion through a function solve) for each matrix, but preserve the full structure of the array.

So far I have had 3 options:

Option 1 : A loop that does exactly what I want, but clumsily and inefficiently.

mat_inv <- array(NA, dims)
for(i in 1:dims[1]) mat_inv[i,,] <- solve(mat_array[i,,])

Option 2 : A function applythat is faster and cleaner, BUT compresses each matrix to a vector.

mat_inv <- apply(mat_array, 1, solve)
dim(mat_inv)
[1]    25 10000

I know that I can set the output sizes according to the input parameters, but I am afraid to do this and ruin the indexing, especially if I had to apply to adjacent measurements (for example, if I wanted to invert by size 2).

3: aaply plyr, , , (4-5x), .

mat_inv <- plyr::aaply(mat_array, 1, solve)

- , base::apply plyr::aaply?

+4

All Articles