【问题标题】:use sp() package to compute the shortest distance between 2 sets of coordinates使用 sp() 包计算两组坐标之间的最短距离
【发布时间】:2018-03-20 16:47:25
【问题描述】:

我有两组坐标(基础和目标)作为两个数据框。

base.df <- data.frame(cbind(LONG = c(-73.94006,-73.95616,-73.86548,-73.99118,-73.99801,
                                 -73.96208,-73.95544,-74.09251,-73.94317,-73.98913),
                            LAT = c(0.78963,40.65378,40.83767,40.75533,40.74759,
                                40.71327,40.81450,40.62554,40.83660,40.57415)))

target.df <- data.frame(cbind(long = c(-74.00754,-74.01252,-74.00525,-74.00594,-74.00668,-73.99290),
                              lat = c(40.70347,40.71007,40.71005,40.71546,40.71976,40.71521)))

我的目标是获取基本数据帧的每一行并使用spDistsN1() 来获得该行(基本)与目标数据帧的每一行之间的不同距离。在许多距离中,我想要最接近的距离(使用min()?)并将最短距离附加到新向量。完成后,我应该只有 10 个数据点可以cbind() 返回基本数据帧。我知道apply() 可能有用,但我对使用它或在 R 中编写函数不是很熟悉,有人可以帮忙吗?

【问题讨论】:

  • 请避免发布图片。以文本格式发布您的数据,以便每个人都可以使用它们。
  • 感谢提醒,我会通过附加可重现代码的方式进行更改
  • 只需使用spDists 而不是spDistsN1。从spDists(as.matrix(base.df),as.matrix(target.df),longlat=TRUE)开始

标签: r apply geospatial distance sp


【解决方案1】:

这是处理任务的一种方法。由于您需要spDistsN1() 的矩阵,因此我将两个数据帧都转换为矩阵对象。在lapply() 中,我计算了base.df 中每一行与target.df 中所有行之间的距离。这将创建十个列表。每个列表代表base.df 中的每一行。你想要做的是在每个列表中寻找一个最小值,你可以用另一个lapply() 来做。最后,我使用bind_cols() 将结果作为out 添加到base.df

library(sp)
library(dplyr)
library(purrr)

base.mtx <- as.matrix(base.df)
target.mtx <- as.matrix(target.df)

lapply(1:nrow(base.df), function(x){
    spDistsN1(pts = target.mtx, pt = base.mtx[x, ])}) %>%
lapply(min) %>%
unlist %>%
bind_cols(base.df, out = .)

        LONG      LAT         out
1  -73.94006  0.78963 39.91389704
2  -73.95616 40.65378  0.07147727
3  -73.86548 40.83767  0.17672665
4  -73.99118 40.75533  0.03880045
5  -73.99801 40.74759  0.02914923
6  -73.96208 40.71327  0.03088100
7  -73.95544 40.81450  0.10612142
8  -74.09251 40.62554  0.11529521
9  -73.94317 40.83660  0.13118157
10 -73.98913 40.57415  0.13062385

【讨论】:

  • 你可以使用spDists。另外,我猜你应该设置longlat=TRUE
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-12
  • 1970-01-01
  • 1970-01-01
  • 2021-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多