Skip to content

Instantly share code, notes, and snippets.

@MattSandy
Last active June 20, 2016 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattSandy/d29ca76911010a91a23bfd22e734f181 to your computer and use it in GitHub Desktop.
Save MattSandy/d29ca76911010a91a23bfd22e734f181 to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment