I have a 3x3x3 matrix (MP) of normalized probabilities (sum up to 1). When I run sample(27,1, MP, replace = T), it returns an integer between 1 and 27, presumably the sequential index of the matrix. I would like to know which matrix element in terms of element indexes (eg row number, column number, z number). When building an array of N dimensions (in this case N=3), how does one determine the order of the elements? In other words, if I took an N dimensional array and put all the elements in a list, how can I map the list to the N dimensional elements?
Use which
with argument arr.ind=TRUE
to return the array indices.
m <- array((1:27)*10, dim=c(3,3,3))
x <- sample(27, 1)
x
# [1] 20
which(m == m[x], arr.ind=TRUE)
# dim1 dim2 dim3
# [1,] 2 1 3