[R] transposing/rotating XY in a 3D array

Kushantha Perera kushanthap at ambaresearch.com
Fri May 15 11:35:25 CEST 2009


Try this:

> x  <- array(1:12,c(3,2,2))
> x
, , 1

     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

, , 2

     [,1] [,2]
[1,]    7   10
[2,]    8   11
[3,]    9   12

> xt <- aperm(x, c(2,1,3))
> xt
, , 1

     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6

, , 2

     [,1] [,2] [,3]
[1,]    7    8    9
[2,]   10   11   12

Good day!

Kushantha Perera | Amba Research

Ph +94 11 235 6281 | Mob +94 77 222 4373

Bangalore * Colombo * London * New York * San José * Singapore * www.ambaresearch.com

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of andzsin
Sent: Friday, May 15, 2009 12:38 PM
To: r-help at r-project.org
Subject: [R] transposing/rotating XY in a 3D array

Dear list,

We have a number of files containing similarly structured data:
file1:
A B C
1 2 3
4 5 6

file2:
A B C
7 8 9
10 11 12
... etc


My part of R receives all these data as an array: 1,2,3... 12 together
with info about dimensions (row,col,fileN) . (

Converting the data into 3D cannot simply done by:
   array(x, c(2,3,2))
because breaks the structure (e.g. 1,3,5 is type mismatch)

array(1:12,c(2,3,2))
, , 1

     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
...

Of course  following R's indexing order (rowIndex is the fastest)
retains the structures, but X and Y dimensions are transposed. (note, c
(2,3,2) => (3,2,2))

array(1:12, c(3,2,2))
, , 1

     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

Its like converting into Japanese vertical reading.
It is not that I cannot get used to it, but I guess it is less error
prone if I have the same order as in the data files.

Now I am using an ad-hoc function (see below) to transpose back the
rotated YX into a  XYZ array, but I'd rather go with built-ins, e.g.
byrow=T, or t()  -- and also without duplicating my data.
THanks for the advice in advance.

Gabor

<code>
transposeXYinXYZ<-function(x){
    y <- array(NA,c(dim(x)[2],dim(x)[1],dim(x)[3]))

    for(i in 1:dim(x)[3]){
        y[,,i] <- t(x[,,i])
    }
    return (y)
}xyz <- array(1:24,c(4,3,2))
yxz <- transpose(x)

xyz
yxz
</code>

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
This e-mail may contain confidential and/or privileged i...{{dropped:10}}




More information about the R-help mailing list