【问题标题】:R find nearest points in matrixR在矩阵中找到最近的点
【发布时间】:2020-10-07 08:26:17
【问题描述】:

R:在矩阵中找到点靠近两个选定点的线。

我有一个区域的长/纬度矩阵。 而且我在这个区域有一个点,有经度和纬度,所以我需要在矩阵中找到最匹配的点。

我已经试过了,但它不起作用:

find.point <- is.numeric(which(abs(matrix[,1]-East)==min(abs(matrix[,1]-East))) 
                               && which(abs(matrix[,2]-North)==min(abs(matrix[,2]-North))))

如何找到 East 最接近 matrix[,1] 以及 North 最接近 matrix[,2] 的点?

【问题讨论】:

  • 欢迎来到 Stack Overflow。请发布一个可重现的示例以及预期的输出。请查看at this link 了解更多信息。
  • 您需要定义“最近点是什么”(欧几里得距离或NorthEast 或其他度量的绝对差异之和)。计算每个点的这个距离,然后你可以使用which.min()

标签: r matrix point


【解决方案1】:

如果没有您提供的具体数据,很难准确地帮助您。但是假设您想用欧几里得距离计算最近的点,并且您的数据与下面有些相似,这可能说明您如何做到这一点:

# Create some toy data
set.seed(1)
pos <- matrix(runif(20), 10, 2)
colnames(pos) <- c("lon", "lat")
print(pos)
#             lon       lat
# [1,] 0.26550866 0.2059746
# [2,] 0.37212390 0.1765568
# [3,] 0.57285336 0.6870228
# [4,] 0.90820779 0.3841037
# [5,] 0.20168193 0.7698414
# [6,] 0.89838968 0.4976992
# [7,] 0.94467527 0.7176185
# [8,] 0.66079779 0.9919061
# [9,] 0.62911404 0.3800352
#[10,] 0.06178627 0.7774452

new.pos <- c(0.5, 0.5) # New position

# Compute distance to points and select nearest index
nearest.idx <- which.min(colSums((t(pos) - new.pos)^2))
nearest.idx
#[1] 9

# Pick out the point
pos[nearest.idx, ]
#      lon       lat 
#0.6291140 0.3800352 

计算距离的行依赖于两个事实:1)R 中的矩阵以列优先顺序存储,2)当向量太短时,R 的重用/重复规则。

【讨论】:

    猜你喜欢
    • 2012-08-18
    • 2020-11-29
    • 2017-03-27
    • 2016-03-03
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 1970-01-01
    相关资源
    最近更新 更多