rarraysolap-cube

How to slice multidimensional data in different ways in R


I have the following data in multiple arrays of dimensions (2,3,2) (i.e. each observation is a cuboid consists of two matrices of size 2x3). Here the number of observations is 3.

y1 <- array(c(4.5,2.7,5.6,9.5,5.4,5.5,4.7,2.9,5.6,9.9,5.0,4.9),   dim = c(2,3,2))
y2 <- array(c(4.6,3.2,5.8,10.2,5.4,5.9,4.9,2.9,5.9,9.9,5.5,4.5),  dim = c(2,3,2))
y3 <- array(c(4.8,2.9,5.7,9.2,5.1,5.2,4.6,2.5,5.4,9.4,5.4,5.8),   dim = c(2,3,2))

I would like to slice this cuboid in three different ways:

Y1 <- matrix(y1,2,6)
Y2 <- matrix(y2,2,6) 
Y3 <- matrix(y3,2,6) 
Y1 <- cbind(t(y1[,,1]),t(y1[,,2]))
Y2 <- cbind(t(y2[,,1]),t(y2[,,2]))
Y3 <- cbind(t(y3[,,1]),t(y3[,,2]))
library(ks)
Y1 <- t(cbind(vec(y1[,,1]),vec(y1[,,2])))
Y2 <- t(cbind(vec(y2[,,1]),vec(y2[,,2])))
Y3 <- t(cbind(vec(y3[,,1]),vec(y3[,,2])))

Is there a more efficient way of slicing the cuboid, rather than manually entering the data?


Solution

  • An option is to place it in a list and do this once

    lst1 <- list(y1, y2, y3)
    lapply(lst1, matrix, nrow = 2, ncol = 6)
    lapply(lst1, function(x) cbind(t(x[,,1]),t(x[,,2])))
    

    and for the third case

    lapply(lst1, function(x) t(cbind(vec(x[,,1]),vec(x[,,2]))))