[R] Matrix to "indexed" vector

Eric Lecoutre lecoutre at stat.ucl.ac.be
Tue Jan 11 14:08:17 CET 2005


Hi Sean,

Here is a way to do that:

idmatrix <- function(m){
   if (!is(m,"matrix")) stop("Please provide a matrix as argument")
   ind <- cbind(as.vector(row(m)),as.vector(col(m)))
   out <- cbind(ind, m[ind])
   return(out)
}


There are others way to provide indexes, such as
 > expand.grid(1:nrow(mm),1:ncol(mm))

Not sure which is the most efficient.

HTH,

Eric


 > data(iris)
 > mm=as.matrix(iris[1:5,1:4])
 > idmatrix(mm)
       [,1] [,2] [,3]
  [1,]    1    1  5.1
  [2,]    2    1  4.9
  [3,]    3    1  4.7
  [4,]    4    1  4.6
  [5,]    5    1  5.0
  [6,]    1    2  3.5
  [7,]    2    2  3.0
  [8,]    3    2  3.2
  [9,]    4    2  3.1
[10,]    5    2  3.6
[11,]    1    3  1.4
[12,]    2    3  1.4
[13,]    3    3  1.3
[14,]    4    3  1.5
[15,]    5    3  1.4
[16,]    1    4  0.2
[17,]    2    4  0.2
[18,]    3    4  0.2
[19,]    4    4  0.2
[20,]    5    4  0.2

At 13:35 11/01/2005, Sean Davis wrote:
>I have a matrix that I want to turn into a transformed matrix that 
>includes the indices from the original matrix and the value.  The matrix 
>is simply real-valued and is square (and large (8k x 8k)).  I want 
>something that looks like (for the 3x3 case):
>
>i       j       value
>1       1       1.0
>1       2       0.783432
>1       3       -0.123482
>2       1       0.783432
>2       2       1.0
>2       3       0.928374
>
>and so on....
>
>I can do this with for loops, but there is likely to be a better way and 
>for my own edification, I would like to see what others would do.
>I am sinking the results to a file for loading into SQL database.
>
>Thanks,
>Sean
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html

Eric Lecoutre
UCL /  Institut de Statistique
Voie du Roman Pays, 20
1348 Louvain-la-Neuve
Belgium

tel: (+32)(0)10473050
lecoutre at stat.ucl.ac.be
http://www.stat.ucl.ac.be/ISpersonnel/lecoutre

If the statistics are boring, then you've got the wrong numbers. -Edward 
Tufte




More information about the R-help mailing list