[R] Matrix to Vector

From: steven mosher <moshersteven_at_gmail.com>
Date: Sat, 05 Jun 2010 11:12:50 -0700


Given a matrix of m*n, I want to reorder it as a vector, using a row major transpose.

so:

> m<-matrix(seq(1,48),nrow=6,byrow=T)
> m

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 2 3 4 5 6 7 8
[2,] 9 10 11 12 13 14 15 16
[3,] 17 18 19 20 21 22 23 24
[4,] 25 26 27 28 29 30 31 32
[5,] 33 34 35 36 37 38 39 40
[6,] 41 42 43 44 45 46 47 48

I want to reorder this as a vector copying by row, so that the final vector has elements ordered thusly: row 1, column 1:N (m[1,1:n]) maps to row 1-n, and m[2,1:n] maps to row[n+1:2n] ...

this obviously is not a solution: as the inherent column major storage paradigm of a matrix
defeats the approach.
> dim(m)<-c(48,1)
> m

      [,1]

 [1,]    1
 [2,]    9
 [3,]   17
 [4,]   25
 [5,]   33
 [6,]   41
 [7,]    2
 [8,]   10
 [9,]   18

[10,] 26
[11,] 34
[12,] 42
[13,] 3
[14,] 11
[15,] 19
[16,] 27
[17,] 35
[18,] 43
[19,] 4
[20,] 12
[21,] 20
[22,] 28
[23,] 36
[24,] 44
[25,] 5
[26,] 13
[27,] 21
[28,] 29
[29,] 37
[30,] 45
[31,] 6
[32,] 14
[33,] 22
[34,] 30
[35,] 38
[36,] 46
[37,] 7
[38,] 15
[39,] 23
[40,] 31
[41,] 39
[42,] 47
[43,] 8
[44,] 16
[45,] 24
[46,] 32
[47,] 40
[48,] 48

I already have a version that loops through the data ( this is actually a portion of a data frame ) to reorder
this into a vector, but I was hoping there was an elegant way

        [[alternative HTML version deleted]]



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. Received on Sat 05 Jun 2010 - 18:15:16 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 05 Jun 2010 - 18:50:27 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive