我有两组坐标(loc和stat),它们都采用以下格式
x y
1 49.68375 8.978462
2 49.99174 8.238287
3 51.30842 12.411870
4 50.70487 6.627252
5 50.70487 6.627252
6 50.37381 8.040766对于第一个数据集中的每个位置(观测位置),我想知道第二个数据集中(气象站)中离它最近的位置。基本上将观测的位置与最近的气象站相匹配,以便以后分析天气影响。
我尝试使用distGeo函数,方法是简单地输入
distGeo(loc, stat, a=6378137, f=1/298.257223563)但这并不起作用,因为loc和stat的格式不正确。
谢谢你的帮忙!
发布于 2020-12-10 00:27:49
试试这个:
outer(seq_len(nrow(loc)), seq_len(nrow(stat)),
function(a,b) geosphere::distGeo(loc[a,], stat[b,]))
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 0.00 88604.79 419299.1 283370.9 283370.9 128560.08
# [2,] 88604.79 0.00 483632.9 194784.6 194784.6 47435.65
# [3,] 419299.12 483632.85 0.0 643230.3 643230.3 494205.86
# [4,] 283370.91 194784.62 643230.3 0.0 0.0 160540.63
# [5,] 283370.91 194784.62 643230.3 0.0 0.0 160540.63
# [6,] 128560.08 47435.65 494205.9 160540.6 160540.6 0.00简要说明:
outer(1:3, 1:4, ...)产生两个向量,它们是笛卡尔乘积,非常类似于expand.grid(1:3,1:4) # Var1 Var2 #1 1 1#2 1#3 1#4 1 2#5 2 2#6 3 2#7 1 3#8 2 3#9 3 3# 10 1 4# 11 2 4# 12 3 4
(仅使用expand.grid演示扩展)
function(a,b)...)被调用一次,其中a被分配整数向量c(1,2,3,1,2,3,1,2,3,1,2,3) (使用我的1:3和1:4示例),b被分配整数向量c(1,1,1,2,2,2,3,3,3,4,4,4).loc[a,]导致更长的框架:如果loc有m行,stat有n行,那么loc[a,]应该有m*n行;类似的stat[b,]也应该有m*n行。这很好用,因为distGeo (和geosphere::中的其他dist*函数)以以下两种方式之一运行:- If either of the arguments have 1 row, then its distance is calculated against all rows of the other argument. Unfortunately, unless you know that `loc` or `stat` will always have just one row, this method doesn't work.
- otherwise, both arguments must have the same number of rows, where the distance is calculated piecewise (1st row of 1st arg with 1st row of 2nd arg; 2nd row 1st arg with 2nd row 2nd arg; etc). This is the method we're prepared for.outer的匿名函数必须自己处理向量化的参数。例如,如果您需要为每一对调用一次geoDist (因此它将被称为m*n次数),那么您必须自己处理,outer不会为您做这件事。在R中有一些构造支持这一点(例如,mapply、Map)或取代outer (Map、expand.grid和do.call),但这是另一个问题。https://stackoverflow.com/questions/65220239
复制相似问题