Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching row-major to column-major dimensions

Tags:

arrays

r

I am putting into R a row-major data as a vector. R interprets this as column-major data and as far as I can see there is no way to tell array to behave in a row-major way.

Let's say I have:

array(1:12, c(3,2,2), 
    dimnames=list(c("r1", "r2", "r3"), c("c1", "c2"),c("t1", "t2"))
)

Which gives:

, , t1

   c1 c2
r1  1  4
r2  2  5
r3  3  6

, , t2

   c1 c2
r1  7 10
r2  8 11
r3  9 12

I want to transform this data to row-major array:

, , t1
   c1 c2
r1  1  2
r2  3  4
r3  5  6

, , t2

   c1 c2
r1  7  8
r2  9 10
r3 11 12
like image 735
Datageek Avatar asked Oct 12 '12 12:10

Datageek


2 Answers

Assuming that your array is in a, i.e. that you already have this array and can't change it at read time, then the following will work:

a <- array(1:12, c(3,2,2), 
           dimnames=list(c("r1", "r2", "r3"), c("c1", "c2"),c("t1", "t2")))

b <- aperm(array(a, dim = c(2,3,2),
                 dimnames = dimnames(a)[2:1]),
           perm = c(2,1,3))
b

>     b
, , 1

   c1 c2
r1  1  2
r2  3  4
r3  5  6

, , 2

   c1 c2
r1  7  8
r2  9 10
r3 11 12
like image 138
Gavin Simpson Avatar answered Sep 28 '22 02:09

Gavin Simpson


The solution:

aperm(array(1:12, c(2,3,2), 
    dimnames=list(c("c1","c2"),c("r1","r2","r3"),c("t1","t2"))),
    perm=c(2,1,3)
)

Note that aperm switches the dimensions. So essentially columns are switched with rows. In addition I needed to change the order of columns and rows in dimnames.

It produces exactly what is needed:

, , t1
   c1 c2
r1  1  2
r2  3  4
r3  5  6

, , t2

   c1 c2
r1  7  8
r2  9 10
r3 11 12
like image 42
Datageek Avatar answered Sep 28 '22 02:09

Datageek