[R] Rotate array by 90°

JS Huang js.huang at protective.com
Fri Feb 6 00:00:14 CET 2015


Hi,

  Here is an implementation.

> rot90
function(a,times=1)
{
  row <- dim(a)[1]
  col <- dim(a)[2]
  dep <- dim(a)[3]
  if (times %% 2 == 1){t <- row; row <- col; col <- t}
  tempA <- array(NA, c(row,col,dep))
  for (i in 1:dep)
  {
    temp <- a[,,i]
    for (j in 1:times)
    {
      temp <- cbind(sapply(1:row,function(x){rev(temp[x,])}))
    }
    tempA[,,i] <- temp
  }
  return(tempA)
}
> A
, , 1

     [,1] [,2] [,3]
[1,] "a"  "b"  "c" 
[2,] "d"  "e"  "f" 
[3,] "g"  "h"  "i" 

, , 2

     [,1] [,2] [,3]
[1,] "j"  "k"  "l" 
[2,] "m"  "n"  "o" 
[3,] "p"  "q"  "r" 

> rot90(A,3)
, , 1

     [,1] [,2] [,3]
[1,] "g"  "d"  "a" 
[2,] "h"  "e"  "b" 
[3,] "i"  "f"  "c" 

, , 2

     [,1] [,2] [,3]
[1,] "p"  "m"  "j" 
[2,] "q"  "n"  "k" 
[3,] "r"  "o"  "l" 




--
View this message in context: http://r.789695.n4.nabble.com/Rotate-array-by-90-tp4702862p4702870.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list