问题
If I have a n dimensional array it can be sliced by a m * n matrix like this
a <- array(1:27,c(3,3,3))
b <- matrix(1:3,3,3)
# This will return the index a[1,1,1] a[2,2,2] and a[3,3,3]
# That is one result for each row in the b matrix
a[b]
# Output
[1] 1 14 27
In the above example the array a is sliced the same way as if it was sliced by each row in the b matrix and the result was combined.
Is there any "effective and easy" way to do a similar slice but to keep some dimensions free? That is slice a n dimensional array with a m * (n-i) dimensional array and get a i+1 dimensional array as result.
# sliceem
# Function for slicing
# Parameters
# a - The n dimensional array to slice
# b - A m*(n-i) matrix
# freeDimension - A vector of length i with dimensions to keep free
# during the slicing
# Returns
# A i dimensional array where the first dimension have m elements and
# each element in the first dimension correspond to a slice using
# a row in the b matrix
#### Examples of desired behavior ####
a <- array(1:27,c(3,3,3))
b <- matrix(1:2,2,2)
sliceem(a,b,freeDimension=2)
# Output (a[1,,1] and a[2,,2])
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 11 14 17
sliceem(a,b,freeDimension=1)
# Output a[,1,1] and a[,2,2]
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 13 14 15
b <- matrix(1:2,2,1)
sliceem(a,b,freeDimension=c(2,3))
# Output (a[1,,] and a[2,,]
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
, , 2
[,1] [,2] [,3]
[1,] 10 13 16
[2,] 11 14 17
, , 3
[,1] [,2] [,3]
[1,] 19 22 25
[2,] 20 23 26
来源:https://stackoverflow.com/questions/31947700/how-to-slice-a-n-dimensional-array-with-a-mn-i-dimensional-matrix-keeping-som