[R] spare matrix replacing values efficiently

Charles C. Berry cberry at tajo.ucsd.edu
Mon Aug 23 02:09:22 CEST 2010


On Sun, 22 Aug 2010, david h shanabrook wrote:

> I am working with a large sparse matrix trying replace all 1 values with 0.  The normal method doesn't work.  Here is a small example:
>
>> x <- Matrix(0,nrow=10,ncol=10,sparse=TRUE)
>> x[,1] <- 1:2
>> x
> 10 x 10 sparse Matrix of class "dgCMatrix"
>
> [1,] 1 . . . . . . . . .
> [2,] 2 . . . . . . . . .
> [3,] 1 . . . . . . . . .
> [4,] 2 . . . . . . . . .
> [5,] 1 . . . . . . . . .
> [6,] 2 . . . . . . . . .
> [7,] 1 . . . . . . . . .
> [8,] 2 . . . . . . . . .
> [9,] 1 . . . . . . . . .
> [10,] 2 . . . . . . . . .
>> x[x==1] <- 0
> Error in .local(x, i, j, ..., value) :
> not-yet-implemented 'Matrix[<-' method
>
>
> Suggestions?  Any solution must be memory efficient as my sparse matrix is large.

Looks like

 	attr( x, "x" )[ attr( x, "x" ) == 1 ] <- 0

should do it, but does not reduce the density of the matrix. In order to 
get that you'll need to do

 	x <- drop0(x)


HTH,

Chuck

>
> dhs
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901



More information about the R-help mailing list