# [R] spinning and flipping arrays

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Mon May 26 23:14:31 CEST 2003

```Bill Rising <brising at louisville.edu> writes:

> On 5/26/2003 15:05, Spencer Graves wrote
>
> >	  I know of no single function to do this;  perhaps someone else does.
> >  I don't have time to write and debug functions to do this myself, but
> >it should be easy enough to write functions like the following:
> >
> >flip3 <-
> >function(x){
> >   n3 <- dim(x)[3]
> >   x[,,n3:1]
> >}
> >spin3 <-
> >function(x, k=1){
> >   n3 <- dim(x)[3]
> >   x[,,1+(((1+k):(n3+k))%%n3)]
> >}
>
> These are pretty much what I'd figured out...
>
> >
> >With a little more work, I could generate functions that would do this
> >for any dimension of arrays with any number of dimensions.  To do that,
> >I might have to compute S-Plus commands using "cmd <- paste(...)" and
> >then execute them using "eval(parse(text=cmd))".

> This last piece is what I think I needed. I had been trying to just put
> the
> /argument/ to the "[" command together, instead of putting together the
> entire command.
>
> Thanks for the tip. I'll keep working on it.

Relying on textual representation always looks dodgy to me. How about

spin <- function(x,amount=c(1,rep(0,length(dim(x))-1))) {
indices <- mapply(function(n,k) (seq(length=n)+k-1)%%n + 1,
dim(x),amount, SIMPLIFY=FALSE)
do.call("[", c(list(x), indices))
}

(Note: mapply() was introduced in 1.7.0). Notice that it is much
easier to use 1:n than to try to generate an empty index for "[".

--
O__  ---- Peter Dalgaard             Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics     2200 Cph. N
(*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907

```