[R] How to calculate the closest distance from a point to a curve?

Spencer Graves spencer.graves at pdf.com
Tue Feb 25 20:24:03 CET 2003

```If you want the closest point to a fitted model, "predict" may work with
the output of the fitting function to generate a column of y's;  see,
e.g, Venables and Ripley, Modern Applied Statistics with S.  Then the
nearest point can be found as Jose Lozano suggested.

Jose Lozano (MEGA) wrote:
>>Hely, R-list
>>
>>Now I have non-parametric curve function, that is,
>>I only use N 2-Dimensional data points to represent
>>this curve, without explicit function formulation.
>>
>
>
> (x,y) gives the points that define the curve (I've generated a circle
> centered at 0)
> (a,b) is the point (I've set it to (2,2))
>
> x<-seq(from=-1,to=+1,length=1000)
> y<-sqrt(1-x^2)
> x<-c(x,x)
> y<-c(y,-y)
> n<-length(x)
> a<-2
> b<-2
>
> The code to find the closest point to (a,b) is:
>
> minimo<-min((1:n)[sqrt((a-x)^2+(b-y)^2)==min(sqrt((a-x)^2+(b-y)^2))])
> cat(x[minimo],y[minimo],"\n")
>
> 0.7077077 0.7065053
>
> Regards
> Jose Lozano
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> http://www.stat.math.ethz.ch/mailman/listinfo/r-help

```