[R] spinning and flipping arrays

Spencer Graves spencer.graves at pdf.com
Mon May 26 21:05:52 CEST 2003


	  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)]
}

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))".

	  Perhaps someone else will reply with a more complete and elegant 
solution.  Until then, I hope this helps.

spencer graves

Bill Rising wrote:
> 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
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help




More information about the R-help mailing list