in R sampling a list of probabilities returns one position. How do I convert that position, to the element index?

StackOverflow https://stackoverflow.com/questions/17667418

Question

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?

Was it helpful?

Solution

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

OTHER TIPS

Technically it's only a matrix if it's two dimensional. What you have is a three dimensional array. If you just try:

array( 1:27, dim = c(3, 3, 3) )

, , 1

     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

, , 2

     [,1] [,2] [,3]
[1,]   10   13   16
[2,]   11   14   17
[3,]   12   15   18

, , 3

     [,1] [,2] [,3]
[1,]   19   22   25
[2,]   20   23   26
[3,]   21   24   27

So you can see from the print out what index corresponds to which sequential value. For example, item 20 in the sequence 1:27 is at [2, 1, 3]. The sequence counts through columns first, then rows then matrices. Knowing that, you don't have to worry so much about keeping the indexes. You can always recreate your array. Furthermore, if you just wanted actually sample your item you could do the following:

y <- array( 1:27, dim = c(3, 3, 3) ) / sum(1:27) # an array like yours
sample(y, 1)

Or, if you wanted to just scramble your whole array you could try sample(y).

BTW, if you really want to be doing what you seem to indicate, when running sample use sample.int. It has higher performance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top