I'm attempting to find the distance between my original point and each point that is in a list.
I found a function someone else produced on here:
euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))
But this appears to sum up the distance of ALL the points from the list.
I would like to have it either return the distance from the first point to each point in the list, or just return which point from that list is the closest to the original point.
referencePointX <- c(102.54)
referencePointY <- c(45.30)
pointListX <- c(76.12, 81.76...)
pointListY <- c(30.13, 39.95...)
Should result in:
30.465477
21.457654
CodePudding user response:
If you put the points in a matrix mat
with one row per point, you can use dist(mat)
to get the distance between every pair of rows. To get the distances from the first row, just select the first nrow(other_points)
(i.e. number of other points) distances with head
.
referencePoint <- c(102.54, 45.30)
pointListX <- c(76.12, 81.76)
pointListY <- c(30.13, 39.95)
other_points <- cbind(pointListX, pointListY)
mat <- rbind(referencePoint, other_points)
mat
#> pointListX pointListY
#> referencePoint 102.54 45.30
#> 76.12 30.13
#> 81.76 39.95
head(dist(mat), nrow(other_points))
#> [1] 30.46548 21.45765
Created on 2021-10-11 by the reprex package (v2.0.1)