[R] extracting values from a 3d array using a matrix from indices

Gabor Grothendieck ggrothendieck at myway.com
Wed Mar 31 22:24:42 CEST 2004


1. Create a matrix A.list each of whose i,j-th entries is a one element list
containing A[i,,j]. Note that A.list and B have the same lengths so
we can use mapply.  With mapply, we can choose the B[k]-th element from the
list represented by A.list[k].  Finally reshape.

# test data
A <- array(1:8,c(2,2,2))
B <- matrix(c(1,2,2,1),2)

# solution
A.list <- apply(A,c(1,3),function(x)list(x))
C <- mapply(A.list,B,FUN=function(x,y)unlist(x)[y])
C <- matrix(C,nrow(A))

# compare to loop solution
C.loop <- matrix(NA,2,2)
for(i in 1:2)for(j in 1:2) C.loop[i,j] <- A[i,B[i,j],j]
identical(C,C.loop) # TRUE

2. The second problem can also be handled with the same A.list in a 
similar way:

C <- sapply(A.list,function(x)which.max(unlist(x)))
C <- matrix(C,nrow(A))

Tamas Papp <tpapp <at> axelero.hu> writes:

: Suppose I have A, an n x m matrix, each element is an integer (an
: index).
: 
: I also have B, an n x l x m array.  I need C, where
: 
: C[n,m] = B[n, A[n, m], m]
: 
: I am currently using loops, what would be the "R way" to do this?
: 
: Another question: let
: 
: A[n, m] <- argmax_l B[n, l, m]
: 
: what would be the nicest way of doing this?  Currently I am using
: max.col and a single loop, going though the n's.
: 
: Background: I solving a discrete-space dynamic programming problem, A
: is the optimal policy, C is the value function.  The structure of the
: problem allows me to use matrices like above, instead of (n * m) x (n
: x m) square matrices.
: 
: Thanks
: 
: Tamas
:




More information about the R-help mailing list