对空间数据使用简单的 for 循环

Using a simple for loop on spatial data

很抱歉,这将是一个 for 循环 101 问题。我正在努力编写一个简单的 for 循环,以根据经纬度数据 table 生成城市之间的距离

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

位置returns以下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

我在任务的这个特定部分的目标是生成 table 每个城市之间的距离(以公里为单位)的相关矩阵性质,对角线为 0(即所有城市都与自己零距离)。

为此,我使用了 sp 包,它需要一个 long-lat 值矩阵,因此我可以按如下方式删除文本:

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)
}

这为我提供了纽约的正确值:

[1]  5436.133 12967.023  6697.541     0.000

所以我想我在整个循环中已经将一个城市覆盖了另一个城市。感谢您帮助我指出我哪里出错了。非常感谢。

首先声明一个矩阵并使用你的迭代器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

我不确定这是否是您要查找的内容

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

您可以尝试 geosphere 包中的 distm 函数:

 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

它 returns 以米为单位的距离,并考虑了地球的几何形状。