# [R] "(de)linearizing" array indices

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Apr 2 14:26:19 CEST 2004

```If you have a choice, just treat the array as a vector (assign a NULL
dim), and when you are done with it, reassign the dimension.  Now, R
arrays are in column-major (Fortran) order, and your code seems to be in
row-major order.  You can use aperm() to go between the two.

On Fri, 2 Apr 2004, Tamas Papp wrote:

> 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?

--
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

```