[R] Speeding up simulation of mean nearest neighbor distances

hadley wickham h.wickham at gmail.com
Wed Oct 3 21:15:05 CEST 2007

It looks like you can pass a vector of neighbourhoods to nndist.

nndist(rpp, k=2:10)

Although you get some warnings, the answers appear to be the same.

all.equal(t(sapply(2:10, function(i) nndist(rpp, k=i))), nndist(rpp, k=2:10))

This might be quite a lot faster, depending on how much work is common
to all neighbourhood sizes.


On 10/3/07, Dale Steele <dale.w.steele at gmail.com> wrote:
> I've written the function below to simulate the mean 1st through nth
> nearest neighbor distances for a random spatial pattern using the
> functions nndist() and runifpoint() from spatsat.  It works, but runs
> relatively slowly - would appreciate suggestions on how to speed up
> this function.  Thanks.  --Dale
> library(spatstat)
> sim.nth.mdist <- function(nth,nsim) {
> D <- matrix(ncol=nth, nrow=nsim)
> for (i in 1:nsim) {
> rpp <- runifpoint(22, win=owin(c(0,1),c(0,1)), giveup=1000)
> for (k in 1:nth) D[i,k] <- mean(nndist(rpp ,k=k))
> }
> D
> }
> sim.nth.mdist(5,100)
> ______________________________________________
> 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.


More information about the R-help mailing list