[R] Calculating distances between points in a data frame?
Sander Oom
slist at oomvanlieshout.net
Mon May 31 17:25:27 CEST 2004
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
More information about the R-help
mailing list