You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R或免费软件中计算200个经纬度采样点的两两距离及lag line分布?

用R实现经纬度采样点两两距离计算与距离区间统计

完全可以用R实现这个需求,以下是具体步骤和代码:

1. 安装并加载必要的包

我们需要用geosphere包计算球面经纬度距离,dplyr和ggplot2用于数据处理和可视化:

install.packages(c("geosphere", "dplyr", "ggplot2"))
library(geosphere)
library(dplyr)
library(ggplot2)

2. 准备采样点数据

假设你的采样点数据是包含lon(经度)和lat(纬度)的数据框,这里用模拟数据示例:

# 模拟200个经纬度采样点(WGS84坐标系)
set.seed(123) # 固定随机种子保证可复现
sample_points <- data.frame(
  lon = runif(200, min = 110, max = 111),
  lat = runif(200, min = 30, max = 31)
)

3. 计算两两采样点的球面距离

用distm()函数计算所有点对的距离,单位默认是米:

# 计算距离矩阵(行和列对应采样点,值为两点间米数距离)
distance_matrix <- distm(sample_points[, c("lon", "lat")], fun = distHaversine)

# 提取上三角矩阵(排除对角线的自身距离,避免重复统计点对)
upper_tri <- upper.tri(distance_matrix, diag = FALSE)
pair_distances <- distance_matrix[upper_tri]

4. 统计各距离区间的样本对数量

自定义你需要的lag区间(比如1米、10米、100米、1000米等),然后统计每个区间的点对数量:

# 定义距离区间(可根据需求调整)
lag_bins <- c(0, 1, 10, 100, 1000, 10000)

# 对距离进行分箱并统计数量
distance_counts <- pair_distances %>%
  cut(breaks = lag_bins, include.lowest = TRUE, right = FALSE) %>%
  table() %>%
  as.data.frame() %>%
  rename(lag_interval = ".", count = "Freq")

# 查看统计结果
print(distance_counts)

5. 可视化距离分布(验证样本量)

用柱状图直观展示各区间的样本对数量:

ggplot(distance_counts, aes(x = lag_interval, y = count)) +
  geom_col(fill = "#2ecc71") +
  labs(title = "采样点对距离区间分布", x = "距离区间(米)", y = "样本对数量") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

补充说明

  • 如果你的数据是其他坐标系,需要先转换为WGS84(EPSG:4326)再计算距离;
  • 可以根据需求调整lag_bins的区间范围,比如增加更大的距离区间;
  • 若样本量很大(远超过200),可以考虑用spdep包的nbdists()函数优化计算效率,但200个点的计算量很小,用上述方法完全足够。

内容的提问来源于stack exchange,提问作者Cheyenne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 07:05:23