[R] working with sparse matrix

Patrick Breheny patrick.breheny at uky.edu
Tue Jun 21 17:44:38 CEST 2011


On 06/21/2011 09:48 AM, davefrederick wrote:
> Hi, I have a 500x 53380 sparse matrix and I am trying to dichotomize it.
> Under sna package I have found event2dichot yet it doesnt recognize sparse
> matrix and requires adjacency matrix or array. I tried to run a simple loop
> code
>
> for (i in 1:500)
> for (j in 1:53380)
> if (matrix[i,j]>0) matrix[i,j]=1

The code you are running does not require a loop:

 > A <- cbind(c(1,0),c(0,2))
 > A
      [,1] [,2]
[1,]    1    0
[2,]    0    2
 > A[A>0] <- 1
 > A
      [,1] [,2]
[1,]    1    0
[2,]    0    1

However, for large sparse matrices, this and other operations will be 
faster if the matrix is explicitly stored as a sparse matrix, as 
implemented in the 'Matrix' package.

-- 
Patrick Breheny
Assistant Professor
Department of Biostatistics
Department of Statistics
University of Kentucky



More information about the R-help mailing list