[R] "(de)linearizing" array indices

Gabor Grothendieck ggrothendieck at myway.com
Fri Apr 2 17:39:07 CEST 2004


R stores its arrays in reverse odometer order where the leftmost
array index varies fastest.  The result of:

matrix(1:4,2) 

shows this.

Your pack and unpack are in odometer
order with the rightmost index varying fastest.  If you were
to move to R's convention then you could move back and
forth by just changing the dimensions (untested):

x <- array(1:64, rep(2,6) )

# array to matrix
xm <- matrix(x, 8) 

or

# other way
x <- array(xm, rep(2,6) )



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

: 
: Hi,
: 
: I have a dynamic programming problem with many state variables, let's
: call them l, n, m, etc.  The transition probabilities are originally
: given in an array form, eg
: 
: transtition[l,m,n,ll,mm,nn]
: 
: give the probability of going from l,m,n to ll,mm,nn.
: 
: However, the numerical solution is best handled when I "flatten" the L
: x M x N state space into a single one (call it S), ie a linear index,
: so I can deal with the problem using simple matrix algebra.  After I
: get the solution, I need to get back the original state variables.
: 
: At the moment I am using two functions like this:
: 
: pack <- function(l, m, n) {
:   (((((l - 1) * M) + m - 1) * N) + n
: }
: 
: unpack <- function(s) {
:   s <- s - 1
:   n <- s %% N + 1
:   s <- s %/% N
:   m <- s %% M + 1
:   l <- s %/% M + 1
:   list(l=l, m=m, n=n)
: }
: 
: to convert between S and L x N x M.
: 
: Sure, it works, but looks ugly as hell.  And I am positive that I am
: abusing the R language with the above code.  So could somebody give me
: a nicer solution?
: 
: Thanks,
: 
: Tamas
:




More information about the R-help mailing list