user3889486
user3889486

Reputation: 656

Using an array as a subindex of a larger dimension array

I have two arrays: P and arr, whose dimension are:

> dim(arr)
[1] 8 2

> dim(P)
[1] 3 8 2

Then, arr has values

> arr
      [,1][,2]
[1,]    2    1
[2,]    1    2
[3,]    1    3
[4,]    1    4
[5,]    2    5
[6,]    2    6
[7,]    2    7
[8,]    2    8

which are intended to be a subindex of the P matrix. So, what I'd like to do is something like this

P[1,arr] 

to obtain the values

P[1,2,1]
P[1,1,2]
P[1,1,3]
...
P[1,2,8]

, but P[1,arr] gives the error

Error in P[1, arr] : incorrect number of dimensions

How can I use arr as a subindex of P?

Upvotes: 1

Views: 32

Answers (1)

BrodieG
BrodieG

Reputation: 52637

Try using cbind to create the indexing matrix:

P[cbind(1, arr)]

though note you may need to change the column order of arr so that the second column comes first since your second dimension is the one with 8 possible values. So maybe:

P[cbind(1, arr[, 2:1])]

Upvotes: 3

Related Questions