Marius Gilbert wrote:
Hello, I'm trying to use R to simulate biological invasions, and got stuck with the following: Is there a function that uses a matrix of occupied/empty values (1 or 0) as input, and producing an output matrix of the same size, with each cell containing the distance to the nearest occupied cell (1) of the input matrix ?
Try this, which uses an internal, undocumented Spatstat function
'exactPdt':
library(spatstat)
nmatdist <- function(aMat){
storage.mode(aMat) <- "logical"
win <- owin(xrange=c(1,ncol(aMat)),yrange=c(1,nrow(aMat)),mask=aMat)
m <- exactPdt(win)
return(m$d)
}
For example, the input matrix: 0 1 1 0 0 0 1 0 0 0 0 0 0 0 0 0
Would produce an output matrix like: 1 0 0 1 1.4 1 0 1 2.2 1.4 1 1.4 2.8 2.2 2.0 2.2
test:
> m1
[,1] [,2] [,3] [,4] [,5]
[1,] 0 0 0 0 0
[2,] 1 0 0 0 0
[3,] 1 1 0 0 0
[4,] 0 0 0 0 0
> nmatdist(m1)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1.414214 2.236068 2.828427 3.605551
[2,] 0 1.000000 1.414214 2.236068 3.162278
[3,] 0 0.000000 1.000000 2.000000 3.000000
[4,] 1 1.000000 1.414214 2.236068 3.162278
looks about right!
Baz