I'm struggling to split an array without using loops. I want to split a 9x9 matrix into nine 3x3 (non-overlapping) matrices. I tried split() to pass a vector as a "factor" grouping without success. I also tried using asplit() without success. I guess I don't understand how "MARGIN" asplit() works. I can get the 3x3 "cubes" using loops, but I'm wondering if there is a way to do it with simple utility functions.
m <- matrix(1:81, 9, 9)
I want to store the 9 resulting 3x3 matrices in a list. The expected result for the first cube is:
cube[[1]]
[,1] [,2] [,3]
[1,] 01 10 19
[2,] 02 11 20
[3,] 03 12 21
I tried
# all these split by row
indices <- matrix(1:9, 3, 3)
cubes <- split(m, as.vector(indices))
indices <- array(1:9, dim = c(3, 3, 9))
cubes <- split(m, as.vector(indices))
indices <- array(matrix(1:9, 3, 3), dim = c(3, 3, 9))
cubes <- split(m, as.vector(indices))
# this gives an error
asplit(m, MARGIN = c(3,1))