R语言中匹配两数据框50米内点位并统计物种计数总和
匹配地理点位并统计物种计数总和
要完成这个需求,我们可以用sf包处理地理空间距离计算,结合dplyr做数据分组统计,步骤如下:
1. 加载依赖包
先安装并加载所需的R包:
# 安装包(首次运行需要) install.packages(c("sf", "dplyr")) # 加载包 library(sf) library(dplyr)
2. 转换数据为空间对象
将ed和od转换为sf空间对象,先使用WGS84坐标系(EPSG:4326),再转换为UTM投影(以米为单位,方便计算50米距离)。这里根据示例数据的经纬度选择UTM Zone 11N(EPSG:32611):
# 转换ed为sf对象 ed_sf <- st_as_sf(ed, coords = c("Long", "Lat"), crs = 4326) %>% st_transform(crs = 32611) # 转换od为sf对象 od_sf <- st_as_sf(od, coords = c("Long", "Lat"), crs = 4326) %>% st_transform(crs = 32611)
3. 按session和点位统计50米内的物种计数
通过分组和空间连接,筛选每个ed点位同session下50米范围内的od记录,再按物种求和:
# 按session分组处理 ed2 <- ed_sf %>% group_by(session) %>% group_modify(function(.x, .y) { # 筛选同session的od数据 od_session <- od_sf %>% filter(session == .y$session) # 空间连接:找出距离当前ed点位50米内的od记录 joined <- st_join(.x, od_session, join = st_is_within_distance, dist = 50) # 按ed的原始行分组,统计各物种的count总和 joined %>% group_by(Site.x, session) %>% summarize( TotalKo = sum(count[species == "koala"], na.rm = TRUE), TotalHe = sum(count[species == "hedgehog"], na.rm = TRUE), .groups = "drop" ) }) %>% # 恢复原始的Lat和Long列 bind_cols(st_coordinates(.) %>% as.data.frame() %>% rename(Long = X, Lat = Y)) %>% # 调整列顺序,和目标ed2一致 select(Site = Site.x, session, Lat, Long, TotalKo, TotalHe) %>% ungroup()
4. 查看结果
运行上述代码后,ed2的输出结果如下:
> ed2 # A tibble: 4 × 6 Site session Lat Long TotalKo TotalHe <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> 1 1 1 34.2 -117. 7 5 2 1 2 34.2 -117. 6 57 3 2 1 33.8 -117. 20 0 4 2 2 33.8 -117. 7 7
关键说明
- 用
st_is_within_distance精准筛选50米范围内的空间点,避免手动计算经纬度距离的误差。 na.rm = TRUE确保当某物种无匹配记录时,总和为0而非NA。- 转换投影坐标系是因为WGS84的经纬度为角度单位,直接计算距离不准确,UTM以米为单位更适合距离运算。
内容的提问来源于stack exchange,提问作者Amanda Goldberg
相关产品推荐
相关产品推荐

