在R中计算两个数据框中点坐标的最近距离并保留所有列
解决方法:找到每个点的最近邻并保留所有列
针对你的需求(4万个点匹配200个点的最近邻,保留全部字段),推荐用sf包的矢量化操作,比rowwise()高效得多,下面是两种优雅的实现方式:
方法1:st_nearest_feature + 列绑定
先通过st_nearest_feature获取每个file1_sf点对应的file2_sf最近点的索引,再绑定属性并计算距离:
library(sf) # 沿用你提供的file1_sf和file2_sf数据 # 获取每个file1点对应的file2最近点索引 nearest_idx <- st_nearest_feature(file1_sf, file2_sf) # 合并file2的属性到file1 result <- cbind(file1_sf, file2_sf[nearest_idx, ]) # 计算两点间的球面距离(单位:米,4326坐标系下默认返回米) result$distance_m <- as.numeric(st_distance(file1_sf, file2_sf[nearest_idx, ], by_element = TRUE))
方法2:st_join直接匹配最近邻
用st_join的join=st_nearest_feature参数一步完成匹配,代码更简洁:
library(sf) library(dplyr) # 用于重命名和列选择 # 一步完成最近邻匹配,保留所有列 result <- st_join(file1_sf, file2_sf, join = st_nearest_feature, left = TRUE) # 计算两点间距离 result$distance_m <- as.numeric(st_distance(result$geometry, result$geometry.y, by_element = TRUE)) # 可选:重命名列让结果更清晰 result <- result %>% rename(point1_geometry = geometry, point2_geometry = geometry.y) %>% select(id, score1, score2, name, feature, distance_m, point1_geometry, point2_geometry)
关键优势
- 效率高:矢量化操作避免了
rowwise()的逐行循环,4万条数据处理速度会快很多 - 保留所有列:两种方法都会完整保留
file1的id、score1、score2和file2的name、feature字段 - 距离准确:针对WGS84(4326)坐标系,
st_distance默认计算球面距离,返回单位为米,如需千米可除以1000
内容的提问来源于stack exchange,提问作者Anisha Garg
相关产品推荐
相关产品推荐

