2

I'd like to calculate the distance between a point and a line in any number (i.e., n) of dimensions.

An excellent example for 2- and 3- dimensions is found here.

Is there a way to generalize this solution to a greater number of dimensions? I have seen other solutions posted previously, but I am not sure exactly how to apply this in R.

Many thanks,

Ken

1 Answers1

0

I have figured out an answer, working from the solution linked in the original question. Posting the R code here for future readers.

two points, A and B, define the line of interest (here length 10)

A <- runif(10, 0.0, 1.0)
B <- runif(10, 0.0, 1.0)

determine distance of the following point, P

P  <- runif(10, 0.0, 1.0)

then work through solution posted in original question

pa = P - A
ba = B - A

t = as.vector((pa %*% ba) / (ba %*% ba))
d = (pa - t * ba)

last, determine the length of d, the vector of interest by taking the sum of squares of its elements, and then its square root

dist = sqrt(sum(d^2))
dist # the solution`