1

This is my data in a matrix. It is lat and long. I want the distance between point 1 and 2, 2 and 3, 3 and 4, etc.

    > mat<-as.matrix(b)
    > mat
            buoy.LON buoy.LAT
      [1,] -86.34816 43.19014
      [2,] -86.34337 43.18656
      [3,] -86.34013 43.18268
      [4,] -86.33468 43.17484
      [5,] -86.33091 43.16549
      [6,] -86.32912 43.15925
      [7,] -86.32786 43.14887

    dis<-distGeo(mat[2,],mat[3,])  #distance in meters
    did
    [1] 505.1605

The above formula works great, but I want to make a loop to do this quickly and I want the data to be added to the matrix.

I created this loop

    for (i in mat[1:169,]) {
      distGeo(mat[i,], mat[i+1,])
      }

but I always get a return of

    196

How can I get the for loop to work correctly, and how can I get the answers added to the matrix?

R.Gould
  • 11
  • 1
  • Possible duplicate of https://stackoverflow.com/q/47115848/3358272 – r2evans Jul 31 '18 at 16:57
  • My answer to that linked question uses `distHaversine`, but I think your use of `geosphere::distGeo` is a better (ellipsoid) calculation. (I should probably update that answer ...) – r2evans Jul 31 '18 at 17:05
  • I have a hard time following that example, when I work with it the n term is producing a problem. should I be defining n n<-numeric() or n<-1? – R.Gould Jul 31 '18 at 17:26
  • The answer doesn't use the `n` variable, it uses the `dplyr::n()` function ... is that what you're referring to? (Do not use any code from the question itself.) – r2evans Jul 31 '18 at 17:34

1 Answers1

0

In Ann Arbor ey? I'm inclined to help.

It looks like distgeo can do exactly what you want without the loop.

distGeo(p1, p2, a=6378137, f=1/298.257223563)

Arguments

p1 longitude/latitude of point(s). Can be a vector of two numbers, a matrix of 2 columns (first column is longitude, second column is latitude) or a SpatialPoints* object

So...

distGeo(mat)
#[1]  556.6029  505.1605  977.2286 1083.0404  708.3580 1157.7188

And to add that to your matrix as a column, you'll need to add a blank space for the first slot (or the last slot depending on what point you want the distance represented):

geodists <- distGeo(mat)
mat <- cbind(mat, dists = c(NA,geodists))
mat
#                            dists
#[1,] -86.34816 43.19014        NA
#[2,] -86.34337 43.18656  556.6029
#[3,] -86.34013 43.18268  505.1605
#[4,] -86.33468 43.17484  977.2286
#[5,] -86.33091 43.16549 1083.0404
#[6,] -86.32912 43.15925  708.3580
#[7,] -86.32786 43.14887 1157.7188

Go blue.

Balter
  • 1,085
  • 6
  • 12