1

Say I have a dataframe such as this:

d<-data.frame(x=c(400.4,400.2,400.1,394.3,396.5),
           y=c(330.2,330.2,330.1,289.9,288.8))

I can calculate the Euclidian distance for the first two rows like this:

dist(d[1:2,]) #0.2

If I wish to do this for every successive row, e.g. distance between rows 1&2, 2&3, 3&4 etc. I have written a for loop, but this is incredibly slow with thousands of rows. Is there a more efficient way of doing this?

jalapic
  • 13,792
  • 8
  • 57
  • 87
  • With [`proxy`](https://cran.r-project.org/package=proxy): `proxy::dist(d[-nrow(d), ], d[-1L, ], method="Euclidean", pairwise=TRUE)` – Alexis Jun 27 '19 at 19:05
  • 1
    You can [extract the diagonal](https://stackoverflow.com/questions/39231961/extract-diagonals-from-a-distance-matrix-in-r) from the result of `dist(d)`: `out <- as.matrix(dist(d)); out[row(out) == col(out) + 1]` – markus Jun 27 '19 at 19:07
  • 5
    `sqrt(diff(d$x)^2 + diff(d$y)^2)` – Henrik Jun 27 '19 at 19:12
  • 1
    Perhaps this: [Computing Euclidean distances between subsequent positions in R](https://stackoverflow.com/questions/18340318/computing-euclidean-distances-between-subsequent-positions-in-r) – Henrik Jun 27 '19 at 19:21

0 Answers0