在空间数据上使用简单的for循环 [英] Using a simple for loop on spatial data

查看:108
本文介绍了在空间数据上使用简单的for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm sorry this is going to be a for loop 101 question. I am struggling to write a simple for loop to generate a table of distances between cities based upon longitude-latitude data

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

locations返回下表:

locations 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

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

My goal in this particular part of the task is to produce a table of the distances (in kilometres) between each of the cities in the nature of a correlation matrix, with the diagonal being 0 (ie all cities are zero distance from themselves).

为此,我使用的是sp程序包,该程序包需要一个经纬度值构成的矩阵,因此可以按如下所示删除文本:

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

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

通过spDistsN1工具,我可以通过比较矩阵中所有城市到一个城市的距离来获取此信息.显然,我可以使用以下表达式来获取所有城市到谢菲尔德的距离(城市或第1行):

The tool spDistsN1 allows me to get this information by comparing the distance all cities in the matrix are from one individual city. Clearly, I can use the following expression to obtain the distances of all cities from Sheffield (city or row# 1):

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

这正确地给出了:

[1]    0.000 9591.009 1329.882 5436.133

但是,为了实现所需的相关矩阵样式输出,我想针对每个城市实现这一点,因此我尝试编写一个for循环:

However, to achieve my desired correlation matrix style output, I want to achieve this for each of the cities, so I tried to write a for loop:

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

这为我提供了正确的NY值:

This gives me the correct values for NY:

[1]  5436.133 12967.023  6697.541     0.000

因此,我想我在整个循环中都将一个城市覆盖了另一个城市.感谢您向我展示我要去哪里的帮助.非常感谢.

So I presume I have overwritten one city by another throughout the loop. I appreciate the help in showing me where I am going wrong. Many thanks.

推荐答案

首先声明一个矩阵,然后使用迭代器i指示要填充的行:

First declare a matrix and use your iterator i to indicate the row to be filled in:

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

这篇关于在空间数据上使用简单的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆