[R] Matrix to "indexed" vector

Sundar Dorai-Raj sundar.dorai-raj at pdf.com
Tue Jan 11 14:01:23 CET 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
> 

How about:

x <- c(1.0, 0.783432, -0.123482, 0.783432, 1.0, 0.928374)
x <- matrix(x, 2, 3, TRUE)
y <- cbind(expand.grid(i = seq(nrow(x)), j = seq(ncol(x))), c(x))
y[order(y[, 1], y[, 2]), ]


   i j      c(x)
1 1 1  1.000000
3 1 2  0.783432
5 1 3 -0.123482
2 2 1  0.783432
4 2 2  1.000000
6 2 3  0.928374


HTH,

--sundar




More information about the R-help mailing list