0

I currently have a column of coordinates(CHR) and longitude & latitude(NUM). I want to create a function that allows to find the distance between each two coordinates. like distance between 1st and 2nd coord, 2nd and 3rd, an so on. I have tried both way to create it.

data$new.Distance[2:n] <- distm(data$Coord[1:(n-1)], data$Coord[2:n], fun = distMeeus)
data$new.Distance[2:n] <- distm(
    c(data$longitude[1:(n-1)], data$latitude[1:(n-1)]), 
    c(data$longitude[2:n], data$latitude[2:n]), 
    fun = distMeeus
)

and I got error message:

ERROR in N-1: non-numeric argument to binary operator. 

How should I fix that? or is there any other way to create this in R? Thank you.

alistaire
  • 42,459
  • 4
  • 77
  • 117
Xichen Yao
  • 15
  • 2
  • If you want sequential differences, you can use `distMeeus` directly: `m <- matrix(rnorm(10), 5); geosphere::distMeeus(m)`. Otherwise, you need to clarify by adding some data [to make your example reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – alistaire Feb 03 '19 at 04:29

1 Answers1

0

Example data.

p <- rbind(c(0,0),c(90,90),c(10,10),c(-120,-45))
colnames(p) <- c("lon", "lat")
p
#      lon lat
#[1,]    0   0
#[2,]   90  90
#[3,]   10  10
#[4,] -120 -45

To get the distance from the first to the second point, second to the third point, and so on, you can do

library(geosphere)
distGeo(p)    
#[1] 10001966  8896111 13879039

Or

distMeeus(p)    
#[1] 10001959  8896115 13879009

To get the distance from all (lon/lat) points to all points, you can use geosphere::distm; providing a distance function of choice (distGeo is the default and the most accurate).

library(geosphere)
distm(p, fun=distGeo)
#         [,1]     [,2]     [,3]     [,4]
#[1,]        0 10001966  1565109 12317881
#[2,] 10001966        0  8896111 14986910
#[3,]  1565109  8896111        0 13879039
#[4,] 12317881 14986910 13879039        0

You can also use raster::pointDistance.

library(raster)
d <- pointDistance(p, lonlat=TRUE)

as.dist(d)
#         1        2        3
#2 10001966                  
#3  1565109  8896111         
#4 12317881 14986910 13879039

It is also possible to get the distances between two sets of points, possibly with a different number of points. For example:

pointDistance(p, p[1:2,], lonlat=TRUE)
#         [,1]     [,2]
#[1,]        0 10001966
#[2,] 10001966        0
#[3,]  1565109  8896111
#[4,] 12317881 14986910
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63