[R] Matrix to "indexed" vector

Peter Dalgaard p.dalgaard at biostat.ku.dk
Tue Jan 11 14:59:46 CET 2005


Sean Davis <sdavis2 at mail.nih.gov> writes:

> On Jan 11, 2005, at 7:55 AM, Dimitris Rizopoulos wrote:
> 
> > mat <- rnorm(9); dim(mat) <- c(3,3)
> > mat
> > ###########
> > cbind(i=rep(1:nrow(mat), each=ncol(mat)),
> >                j=rep(1:ncol(mat), nrow(mat)), value=c(t(mat)))
> >
> That will do it.  Thanks!

Also, almost the same (you might want to change the column names and
the levels):

> as.data.frame(as.table(mat))
   Var1 Var2        Freq
1     A    A  1.30228891
2     B    A  0.03432453
3     C    A  0.84913086
4     D    A -0.72574037
5     A    B  0.57836049
6     B    B -1.53737385
7     C    B -0.73390887
8     D    B  1.01061902
9     A    C  0.27826502
10    B    C -2.50497059
11    C    C -0.57292384
12    D    C  2.13511711

and

> cbind(i=c(row(mat)),j=c(col(mat)),value=c(mat))
      i j       value
 [1,] 1 1  1.30228891
 [2,] 2 1  0.03432453
 [3,] 3 1  0.84913086
 [4,] 4 1 -0.72574037
 [5,] 1 2  0.57836049
 [6,] 2 2 -1.53737385
 [7,] 3 2 -0.73390887
 [8,] 4 2  1.01061902
 [9,] 1 3  0.27826502
[10,] 2 3 -2.50497059
[11,] 3 3 -0.57292384
[12,] 4 3  2.13511711

(In both cases you need a transpose or reordering if you want j to
vary the fastest.)

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list