built-in and idiomatic Mod(diff(x)+1i*diff(y))
or even better Mod(diff(x+1i*y)) Rich On Tue, Feb 15, 2011 at 10:24 PM, William Dunlap <[email protected]> wrote: > > -----Original Message----- > > From: [email protected] > > [mailto:[email protected]] On Behalf Of Darcy Webber > > Sent: Tuesday, February 15, 2011 4:10 PM > > To: [email protected] > > Subject: [R] distance between consecutive points > > > > Dear R users, > > > > I have two coloumns of data, say x and y, referring to a list of > > points in 2D space. I am trying to develop a code that will give me > > the distances (using Pythagoras) between consecutive points (xi,yi) > > and (xi+1,yi+1). So far I have come up with the following: > > > > for (i in 1:length(x)) d<-sqrt((x[i+1]-x[i])^2+(y[i+1]-y[i])^2) > > You want to assign to d[i] (where d is a preallocated numeric > vector of length length(x)-1), not d, so you save all the > distances and you don't want to do this for i==length(n), > as there is no x[i+1] then. > > Here is more idiomatic R code that does it with a loop: > > hypot <- function(x,y)sqrt(x^2 + y^2) # must be a built-in for this > > d <- hypot( diff(x), diff(y) ) > > d > [1] 0.01 > > Bill Dunlap > Spotfire, TIBCO Software > wdunlap tibco.com > > > > For example, if I use the two points (note, I have hundreds > > of points for x,y) > > x<-c(64.59,64.60) > > y<-c(-179.28,-179.28) > > > > d should be 0.01. > > > > But it just doesn't give me the correct answer and I can't figure out > > why. Any help would be much appreciated. > > > > Cheers, > > D'Arcy > > > > ______________________________________________ > > [email protected] mailing list > > https://stat.ethz.ch/mailman/listinfo/r-help > > PLEASE do read the posting guide > > http://www.R-project.org/posting-guide.html<http://www.r-project.org/posting-guide.html> > > and provide commented, minimal, self-contained, reproducible code. > > > > ______________________________________________ > [email protected] mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html<http://www.r-project.org/posting-guide.html> > and provide commented, minimal, self-contained, reproducible code. > [[alternative HTML version deleted]] ______________________________________________ [email protected] mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.

