提问者:小点点

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


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

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

locations返回下表:

       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

我在任务的这一部分的目标是制作一个表格,列出每个城市之间的距离(以公里为单位),这是一个相关矩阵的性质,对角线为0(即所有城市与自己的距离为零)。

为此,我使用sp包,它需要一个长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)
}

这给了我NY的正确值:

[1]  5436.133 12967.023  6697.541     0.000

所以我想我已经在整个循环中用另一个城市覆盖了一个城市。我很感激你帮助我指出了我的错误。非常感谢。


共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

匿名用户

我不确定这是不是你要找的

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

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