MattSandy
6/20/2016 - 4:51 PM

Find the Minimum Distance Between Two Points, and Their Coordinates

Find the Minimum Distance Between Two Points, and Their Coordinates

set.seed(1)
df <- data.frame(x=rnorm(10), y=rnorm(10))
d1 <- dist(df)

min(d1)
#0.2036045
which.min(d1)
#43
df[combn(row.names(df),2)[,match(min(d1),d1)],]
#           x         y
# 8 0.7383247 0.9438362
# 9 0.5757814 0.8212212

combinations <- data.frame(t(combn(row.names(df),2)))
combinations$dist <- apply(combinations,1,function(x) {
  return(dist(df[x,]))
})
combinations[which.min(combinations$dist),]
# X1 X2      dist
# 8  9 0.2036045