[R] Matrix to "indexed" vector

Douglas Bates bates at wisc.edu
Tue Jan 11 14:34:52 CET 2005


Sundar Dorai-Raj wrote:
> 
> 
> 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
> 
> ______________________________________________
> 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

This form is called the 'triplet' form of a sparse matrix and is used in 
the 'tripletMatrix' class from the Matrix package.  You could do the 
transformation as

 > library(Matrix)
 > mm <- matrix(rnorm(12), nc = 4)
 > mm
            [,1]       [,2]       [,3]        [,4]
[1,]  0.3270100  2.3091426 -0.3843992  1.13819897
[2,] -0.1161578 -0.4877587 -0.0709391 -0.91308167
[3,]  0.9652397 -0.3230332 -1.3011591 -0.03514905

 > as(as(mm, 'cscMatrix'), 'tripletMatrix')
An object of class "tripletMatrix"
Slot "i":
  [1] 0 1 2 0 1 2 0 1 2 0 1 2

Slot "j":
  [1] 0 0 0 1 1 1 2 2 2 3 3 3

Slot "x":
  [1]  0.32700997 -0.11615783  0.96523972  2.30914265 -0.48775866 
-0.32303318
  [7] -0.38439915 -0.07093910 -1.30115907  1.13819897 -0.91308167 
-0.03514905

Slot "Dim":
[1] 3 4

(There should be a direct coersion method from the "matrix" class to the 
"tripletMatrix" class and there will be in the next release of the 
Matrix package.  For the time being you must go through the "cscMatrix" 
class as an intermediate.)

Note that the index vectors for the tripletMatrix class are 0-based 
indices, not 1-based.  If you want to make them 1-based then just add 1 
to the 'i' and 'j' slots.




More information about the R-help mailing list