[R] spinning and flipping arrays

Bill Rising brising at louisville.edu
Mon May 26 19:39:23 CEST 2003


Hello people,

Is there some simple way of spinning and/or flipping arrays in R? 
Here's what I mean.

Suppose that foo is a 2x3x4 array with the following contents: (I know 
this is different than typing 'foo' at and R prompt, but I'm so used to 
row major order from using APL, I have a hard time with R's output)

> foo[1,,]
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    5    6    7    8
[3,]    9   10   11   12

> foo[2,,]
     [,1] [,2] [,3] [,4]
[1,]   13   14   15   16
[2,]   17   18   19   20
[3,]   21   22   23   24

flipping foo around its last coordinate would be done via

> flipfoo <- foo[,,4:1]

> flipfoo[1,,]
     [,1] [,2] [,3] [,4]
[1,]    4    3    2    1
[2,]    8    7    6    5
[3,]   12   11   10    9
> flipfoo[2,,]
     [,1] [,2] [,3] [,4]
[1,]   16   15   14   13
[2,]   20   19   18   17
[3,]   24   23   22   21

(a more general method would allow specifying the axis around which to 
reverse the subscripts)

spinning corresponds to shifting the coordinates by possibly different 
amounts along one axis.

I need these to manipulate a dataset, and have been tearing my hair out 
for a day and a half trying to figure out how to do it in R. Matlab has a 
few user-written utilities. APL has it built in as an operator. R 
*should* be able to do it, but I'm too new to R to figure it out. It 
could be easily done in general by any number of ways if only I could 
figure out how to turn a string (like ",,4:1") into the argument for "[". 
Nothing I've tried or searched for works, but I suspect I'm being a bit 
obtuse.

Thanks for any and all hints.

Bill




More information about the R-help mailing list