On Aug 26, 2009, at 12:53 PM, milton ruser wrote:
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(...).
First the wrong way and then the right way:
> mymat[mymat==1] <- runif(1,min=0.4,max=0.7)
> mymat
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
[1,] 0.4573161 0 0 2 0 0 0 0 0 3 0
[2,] 0.4573161 0 0 2 0 2 0 0 0 0 0
[3,] 0.4573161 0 0 2 0 2 0 0 4 0 0
[4,] 0.0000000 0 0 0 0 2 3 0 4 0 0
[5,] 0.0000000 0 0 0 0 0 3 0 3 0 0
All the values are the same, clearly not what was desired.
Put it back to your starting point:
> 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)
# So supply the proper number of random realizations:
> mymat[mymat==1] <- runif(sum(mymat==1),min=0.4,max=0.7)
> mymat
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
[1,] 0.5745665 0 0 2 0 0 0 0 0 3 0
[2,] 0.6956418 0 0 2 0 2 0 0 0 0 0
[3,] 0.6935466 0 0 2 0 2 0 0 4 0 0
[4,] 0.0000000 0 0 0 0 2 3 0 4 0 0
[5,] 0.0000000 0 0 0 0 0 3 0 3 0 0
If you want to supply a matrix of max and min values for the other
integers there would probably be an *apply approach that could be used.
I can do it using for(), but it is very time expensive.
Any help are welcome.
cheers
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
______________________________________________
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.