# [R] Speeding up simulation of mean nearest neighbor distances

jim holtman jholtman at gmail.com
Wed Oct 3 20:26:14 CEST 2007

```If you take a look at what is happening with Rprof, you will see that
most of the time (96.6%) is being taken in the 'nndist' function, so
if you want to improve your algorithm, can you somehow reduce the
number of time you call it, or find a different approach.  So it is a
function of the algorithm you have chosen and unless you want to delve
into 'nndist' and optimize it, then you will have to evaluate other
approaches.

\$by.total
total.time total.pct self.time self.pct
sim.nth.mdist           11.82     100.0      0.02      0.2
mean                    11.62      98.3      0.10      0.8
nndist                  11.42      96.6      0.02      0.2
nndist.ppp              11.40      96.4      0.10      0.8
nndist.default          11.26      95.3      0.14      1.2
apply                    9.78      82.7      0.58      4.9
FUN                      8.86      75.0      0.18      1.5
sort                     8.68      73.4      1.58     13.4
sort.default             7.04      59.6      0.14      1.2

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
> and provide commented, minimal, self-contained, reproducible code.
>

--
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?

```