简体   繁体   中英

a fast way to calculate orthogonal distance of a point to y=x in R

I have a bunch of points that lie around y=x (see the examples below), and I hope to calculate the orthogonal distance of each point to this y=x . Suppose that a point has coordinates (a,b) , then it's easy to see the projected point on the y=x has coordinates ((a+b)/2, (a+b)/2) . I use the following native codes for the calculation, but I think I need a faster one without the for loops. Thank you very much!

set.seed(999)
n=50
typ.ord = seq(-2,3, length=n)   # x-axis
#
good.ord = sort(c(rnorm(n/2, typ.ord[1:n/2]+1,0.1),rnorm(n/2,typ.ord[(n/2+1):n]-0.5,0.1)))
y.min = min(good.ord)
y.max = max(good.ord)
#
plot(typ.ord, good.ord, col="green", ylim=c(y.min, y.max))
abline(0,1, col="blue")
# 
# a = typ.ord
# b = good.ord
cal.orth.dist = function(n, typ.ord, good.ord){
  good.mid.pts = (typ.ord + good.ord)/2
  orth.dist = numeric(n)
  for (i in 1:n){
    num.mat = rbind(rep(good.mid.pts[i],2), c(typ.ord[i], good.ord[i]))
    orth.dist[i] = dist(num.mat)
  }
  return(orth.dist)
}
good.dist = cal.orth.dist(50, typ.ord, good.ord)
sum(good.dist)

As easy as

good.dist <- sqrt((good.ord - typ.ord)^2 / 2)

It all boils down to compute the distance between a point and a line. In the 2D case of y = x , this becomes particularly easy (try it yourself).

In the more general case (extending to other lines in possibly more than 2-D space), you can use the following. It works by constructing a projection matrix P from the subspace (here the vector A ) onto which you want to project the points x . Subtracting the projected component from the points leaves the orthogonal component, for which it's easy to calculate the distances.

x <- cbind(typ.ord, good.ord)          # Points to be projected
A <- c(1,1)                            # Subspace to project onto
P <- A %*% solve(t(A) %*% A) %*% t(A)  # Projection matrix P_A = A (A^T A)^-1 A^T
dists <- sqrt(rowSums(x - x %*% P)^2)  # Lengths of orthogonal residuals

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM