简体   繁体   中英

How to find a spatial distance between each pair of coordinated locations in R

I tried to find the distance between each pair of coordinated locations. Then, I would like to save it as matrix. However, I would like this matrix includes the number of the location.

I wrote my code but it only gives me the distance between two locations.

Here is my try:

library(sp)
data("meuse")
SpDist1 <- function(data) {

  dist <- spDists(meuse)
  n <- length(data)
  for (i in 1:(n - 1)) {
    for (j in (i+1):n) {
      d <- dist[i,j]
      dd <- (c(i,j,d))
    }

}
  return(dd)
}

I have also tried the following code (which calculate the distance between every location with all other locations and return vectors. For example, it calculates the distance between the first location and all other location and return a vector and so on for the other locations. However, the problem here is that there are many redundant measurements.

res <-lapply(1:n, function(i) spDistsN1(meuse, meuse[i,]))

I would like to remove the distance that is larger than 700 m.

The idea of storing indices with data strikes me as odd, but presumably you have a motivation for doing so. It would help to write a utility function that takes a 2-dimensional matrix and expands it to an array:

pad.matrix <- function(A){
  m <- nrow(A)
  n <- ncol(A)
  face1 <- matrix(rep(1:m,n),nrow = m)
  face2 <- t(matrix(rep(1:n,m),nrow = n))
  array(c(face1,face2,A),dim = c(m,n,3))
}

Then, the dd that you are trying to construct might be:

library(sp)
data("meuse")
dist <- spDists(meuse)
dd <- pad.matrix(dist)

For example, dd[4,5,] = 4.0000 5.0000 199.9696 , which is basically the same information as dist[4,5] = 199.9696

On Edit : Here is a way to create an expanded 2-d matrix from your distance matrix:

library(sp)
data("meuse")
dist <- spDists(meuse)
d <- expand.grid(1:nrow(dist),1:nrow(dist))
d$dist <- apply(d,1,function(r)dist[r[1],r[2]])
dd <- as.matrix(d)
dimnames(dd) <- NULL
dd <- dd[dd[,1] < dd[,2],]
dd <- dd[order(dd[,1]),]

For example:

> head(dd)
     [,1] [,2]      [,3]
[1,]    1    2  147.0884
[2,]    1    3  440.7263
[3,]    1    4  889.3523
[4,]    1    5  953.7662
[5,]    1    6 1025.6077
[6,]    1    7  797.5861

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM