## A function to find the nearest neighbor of a point require (class) nearest <- function (X, n, k=3) ## Find k nearest neighbors of X[n, ] in the data frame ## or matrix X, utilizing function knn1 k-times. { N <- nrow(X) # inds contains the indices of nearest neighbors inds <- c(n); i <- 0 while (i < k) { # use knn1 for one index... j <- as.integer(knn1(X [-inds, ], X[n, ], 1:(N-length(inds)))) # ...and change to true index of neighbor inds <- c(inds, setdiff(1:N, inds)[j]) i <- i+1 } # return nearest neighbor indices (without n, of course) return(inds[-1]) } ## A function to calculate the spatial statistic discussed in the midterm spat.stat <- function(X){ n <- nrow(X) Out <- real() for(i in 1:n){ Out[i] <- sqrt( (X[i,1]- X[nearest(X, i, 1),1])^2 + (X[i,2]- X[nearest(X,i,1),2])^2) } Out <- mean(Out) return(Out) }