set the problem of drawing lines to join the nearest neighbour pairs of any given set of points (x, y) that are mapped in two dimensions. There are three steps to the computing:
compute the distance to every neighbour;
identify the smallest neighbour distance for each individual;
use these minimal distances to identify all the nearest neighbours.
x <- runif(100)
y <- runif(100)
par(pty="s")
plot(x,y,pch=21,bg="red")
distance <- function(x1,y1,x2,y2) sqrt((x2 - x1)ˆ2 + (y2 - y1)ˆ2)
r <- numeric(100)
nn <- numeric(100)
d <- numeric(100)
for (i in 1:100) {
for (k in 1:100) d[k] <- distance(x[i],y[i],x[k],y[k])
r[i] <- min(d[-i])
nn[i] <- which(d==min(d[-i]))
}
for (i in 1:100) lines(c(x[i],x[nn[i]]),c(y[i],y[nn[i]]),col="green")
topd <- 1-y
rightd <- 1-x
edge <- pmin(x,y,topd,rightd)
sum(edge<r)
plot(x,y,pch=16)
id <- which(edge<r)
points(x[id],y[id],col="red",cex=1.5,lwd=2)
mean(r)
mean(r[-id])
26.2.1 Tessellation
install.packages("tripack")
library(tripack)
x<-runif(100)
y<-runif(100)
map<-voronoi.mosaic(x,y)
plot(x,y,pch=16,col="green")
plot.voronoi(map,pch=16,add=TRUE)