[R] Calculating distances between points in a data frame?

Wolski wolski at molgen.mpg.de
Mon May 31 17:37:32 CEST 2004


Hi!
It may bee that the function dist can be of some use to you?
?diff

I have something like this in mind. (you do not need a loop.)
XY$DistXY <- sqrt(diff(X)^2+diff(Y)^2)

Have fun trying.
Sincerely Eryk

*********** REPLY SEPARATOR  ***********

On 5/31/2004 at 5:25 PM Sander Oom wrote:

>Dear list,
>
>I would like to calculate the distance between consecutive points in a
>data 
>frame. Of course the first point in the data frame does not have a point
>of 
>origin, and should get a value NA. I have tried two different loops, which 
>both result in error:
>
> > num <- seq(0,10,1)
> > X <- seq(0,30,3)
> > Y <- seq(0,40,4)
> > XY <- data.frame(num, X, Y)
> > attach(XY)
> > summary(XY)
>       num             X              Y
>  Min.   : 0.0   Min.   : 0.0   Min.   : 0
>  1st Qu.: 2.5   1st Qu.: 7.5   1st Qu.:10
>  Median : 5.0   Median :15.0   Median :20
>  Mean   : 5.0   Mean   :15.0   Mean   :20
>  3rd Qu.: 7.5   3rd Qu.:22.5   3rd Qu.:30
>  Max.   :10.0   Max.   :30.0   Max.   :40
> > plot(X,Y)
> > rngNum <- range(num)
> > for (i in rngNum){
>+     XY$DistXY[i] <- sqrt( ((X[i]-X[i-1])^2) + ((Y[i]-Y[i-1])^2) )
>+ }
>Error in "$<-.data.frame"(`*tmp*`, "DistXY", value = sqrt(((X[i] - X[i -  :
>         replacement has 10 rows, data has 11
> > for (i in rngNum){
>+     XY$DistXY2[i] <- ifelse(i=min(rngNum), NA, sqrt(((X[i]-X[i-1])^2) + 
>((Y[i]-Y[i-1])^2)) )
>+ }
>Error in ifelse(i = min(rngNum), NA, sqrt(((X[i] - X[i - 1])^2) + ((Y[i] -
> :
>         unused argument(s) (i ...)
> > detach(XY)
> >
>
>Any suggestions much appreciated,
>
>Sander Oom.
>
>
>--------------------------------------------------------------
>Dr. Sander P. Oom
>Animal, Plant and Environmental Sciences
>University of the Witwatersrand
>Private Bag 3
>Wits 2050
>South Africa
>
>Tel (work)      +27 (0)11 717 64 04
>Tel (home)      +27 (0)18 297 44 51
>Fax             +27 (0)18 299 24 64
>
>Email   sander at oomvanlieshout.net
>Web     www.oomvanlieshout.net/sander
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html



Dipl. bio-chem. Eryk Witold Wolski    @    MPI-Moleculare Genetic   
Ihnestrasse 63-73 14195 Berlin       'v'    
tel: 0049-30-83875219               /   \    
mail: wolski at molgen.mpg.de        ---W-W----    http://www.molgen.mpg.de/~wolski




More information about the R-help mailing list