Bill Dunlap TIBCO Software Inc - Spotfire Division wdunlap tibco.com
> -----Original Message----- > From: r-help-boun...@r-project.org > [mailto:r-help-boun...@r-project.org] On Behalf Of milton ruser > Sent: Wednesday, August 26, 2009 9:54 AM > To: r-help@r-project.org > Subject: [R] changing equal values on matrix by same random number > > Dear all, > > I have about 30,000 matrix (512x512), with values from 1 to N. > Each value on a matrix represent a habitat patch on my > matrix (i.e. my landscape). Non-habitat are stored as ZERO. > No I need to change each 1-to-N values for the same random > number. > > Just supose my matrix is: > mymat<-matrix(c(1,1,1,0,0,0,0,0,0,0,0, > 0,0,0,0,2,2,2,0,0,0,0, > 0,0,0,0,2,2,2,0,0,0,0, > 3,3,0,0,0,0,0,0,0,4,4, > 3,3,0,0,0,0,0,0,0,0,0), nrow=5) > > I would like that all cells with 1 come to be > runif(1,min=0.4, max=0.7), and cells with 2 > be replace by another runif(...). > > I can do it using for(), but it is very time expensive. > Any help are welcome. Is the following what you want? It uses the small integers in mymat as indices into a vector of N random numbers. > mymat [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [1,] 1 0 0 2 0 0 0 0 0 3 0 [2,] 1 0 0 2 0 2 0 0 0 0 0 [3,] 1 0 0 2 0 2 0 0 4 0 0 [4,] 0 0 0 0 0 2 3 0 4 0 0 [5,] 0 0 0 0 0 0 3 0 3 0 0 > range(unique(mymat)) [1] 0 4 > f<-function(mat){ N<-max(mat) tmp <- mat[mat>0] tmp <- runif(N, 0.4, 0.7)[tmp] mat[mat>0] <- tmp mat } > f(mymat) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [1,] 0.5361427 0 0 0.6727491 0 0.0000000 0.0000000 0 0.0000000 [2,] 0.5361427 0 0 0.6727491 0 0.6727491 0.0000000 0 0.0000000 [3,] 0.5361427 0 0 0.6727491 0 0.6727491 0.0000000 0 0.5357566 [4,] 0.0000000 0 0 0.0000000 0 0.6727491 0.6417832 0 0.5357566 [5,] 0.0000000 0 0 0.0000000 0 0.0000000 0.6417832 0 0.6417832 [,10] [,11] [1,] 0.6417832 0 [2,] 0.0000000 0 [3,] 0.0000000 0 [4,] 0.0000000 0 [5,] 0.0000000 0 The 3 lines involving tmp could be collapsed into one, making things more obscure mat[mat>0] <- runif(N, 0.4, 0.7)[mat[mat>0]] Bill Dunlap TIBCO Software Inc - Spotfire Division wdunlap tibco.com > cheers > > milton > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@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. > ______________________________________________ R-help@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.