Using a simple loop for spatial data

Sorry this will be a question for the cycle. I'm struggling to write a simple loop to create a table of distances between cities based on latitude longitude data

locations <-read.csv("distances.csv")

returns the following table:

       City Type       long      lat
1 Sheffield  EUR  -1.470085 53.38113
2        HK WRLD 114.109497 22.39643
3    Venice  EUR  12.315515 45.44085
4  New York WRLD -74.005941 40.71278

My goal in this particular part of the task is to create a table of distances (in kilometers) between each of the cities in the nature of a correlation matrix with a diagonal of 0 (i.e., all cities at a zero distance from themselves).

To do this, I use the sp package, which requires a long-lat matrix of values, so I can remove the text as follows:

datmax <- data.matrix(locations)
datmax2 <- datmax[,-1:-2]

spDistsN1 , , . , ( № 1):

km <- spDistsN1(datmax2, datmax2[1,], longlat=TRUE)

:

[1]    0.000 9591.009 1329.882 5436.133

, , , for:

for (i in 1:nrow(datmax2)){
  kmnew <- spDistsN1(datmax2, datmax2[i,], longlat=TRUE)
}

NY:

[1]  5436.133 12967.023  6697.541     0.000

, . , , . .

+4
3

i, , :

kmnew <- matrix(NA, nrow=4, ncol=4)
for (i in 1:nrow(datmax2)){
  kmnew[i,] <- spDistsN1(datmax2, datmax2[i,], longlat=TRUE)
}

colnames(kmnew) <- locations$City
rownames(kmnew) <- locations$City

> kmnew

          Sheffield        HK   Venice  New York
Sheffield     0.000  9591.009 1329.882  5436.134
HK         9591.009     0.000 9134.698 12967.024
Venice     1329.882  9134.698    0.000  6697.541
New York   5436.134 12967.024 6697.541     0.000
+4

, ,

library(sp)

# Provide data for reproducibility
locations <- data.frame(City=c("Sheffield", "HK", "Venice", "New York"),
                    Type=c("EUR", "WRLD", "EUR", "WRLD"),
                    long=c(-1.470085, 114.109497, 12.315515, -74.005941),
                    lat=c(53.38113, 22.39643, 45.44085, 40.71278))

km <- apply(as.matrix(locations[, c(-1, -2)]), 1, function(x){
  spDistsN1(as.matrix(locations[, c(-1, -2)]), x, longlat=TRUE)
})

km <- data.frame(locations[, 1],  km)
names(km) <- c("City", as.character(locations[, 1]))
km

       City Sheffield        HK   Venice  New York
1 Sheffield     0.000  9591.009 1329.882  5436.134
2        HK  9591.009     0.000 9134.698 12967.024
3    Venice  1329.882  9134.698    0.000  6697.541
4  New York  5436.134 12967.024 6697.541     0.000
+2

You can try the distmfunction from the package geosphere:

 distm(datmax2)
 #        [,1]     [,2]    [,3]     [,4]
 #[1,]       0  9586671 1329405  5427956
 #[2,] 9586671        0 9130036 12962132
 #[3,] 1329405  9130036       0  6687416
 #[4,] 5427956 12962132 6687416        0

It returns the distance in meters and takes into account the geometry of the earth.

+1
source

All Articles