R语言计算参考点到点列表各点欧氏距离并查找最近点
R语言实现参考点到多点点距离计算
问题根因
你之前使用的函数中调用了sum()对所有坐标差的平方求和,因此只会返回单个汇总值,R的算术运算默认支持向量逐元素计算,去掉sum()即可实现逐点距离计算。
方案1:返回所有点到参考点的对应距离
代码实现如下:
# 定义计算全量距离的函数 calc_all_euc <- function(ref_x, ref_y, point_x, point_y) { sqrt((ref_x - point_x)^2 + (ref_y - point_y)^2) } # 示例数据 referencePointX <- 102.54 referencePointY <- 45.30 pointListX <- c(76.12, 81.76) pointListY <- c(30.13, 39.95) # 调用函数得到所有距离 all_distance <- calc_all_euc(referencePointX, referencePointY, pointListX, pointListY) print(all_distance)
输出结果和你的预期一致:
[1] 30.465477 21.457654
方案2:直接返回距离最近的点
直接基于逐点距离取最小值对应的坐标即可:
# 定义获取最近点的函数 get_nearest_point <- function(ref_x, ref_y, point_x, point_y) { distances <- sqrt((ref_x - point_x)^2 + (ref_y - point_y)^2) min_index <- which.min(distances) return(c(x = point_x[min_index], y = point_y[min_index], distance = distances[min_index])) } # 调用函数 nearest_point <- get_nearest_point(referencePointX, referencePointY, pointListX, pointListY) print(nearest_point)
输出示例:
x y distance 81.76000 39.95000 21.45765
内容的提问来源于stack exchange,提问作者Loons22
相关产品推荐
相关产品推荐

