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

如何在sf::st_intersection()中对重叠几何的属性进行求和汇总?

解决几何重叠区域属性值求和的问题

我明白你的需求啦——你想要在几何图形的重叠区域把对应的属性值求和,而不是保留单个对象的属性。咱们来修改一下你的代码,实现这个功能:

完整实现代码

library(devtools)
install_github("r-spatial/sf")
library(sf)
library(purrr) # 用于处理列表类型的origins字段

# 创建原始多边形对象
m = rbind(c(0,0), c(1,0), c(1,1), c(0,1), c(0,0))
p = st_polygon(list(m))
n = rbind(c(0.5,0.5), c(1.5,0.5), c(1.5,1.5), c(0.5,1.5), c(0.5,0.5))
q = st_polygon(list(n))
s = st_sfc(list(p, q))
sf = st_sf(s, att=c(1,1))

# 计算几何相交,得到分割后的所有区域
d = st_intersection(sf)
d$id <- 1:nrow(d)

# 核心步骤:根据origins字段对原始属性值求和
d$att_sum <- map_dbl(d$origins, ~sum(sf$att[.x]))

# 查看结果
print(d)
# 可视化验证
plot(d['att_sum'])
plot(st_centroid(d['att_sum']), add = TRUE, col = 'red')

关键逻辑解释

  • st_intersection返回的结果中,origins字段是一个列表,每个元素记录了覆盖当前区域的原始图形的索引
  • n.overlaps字段已经告诉我们每个区域被几个图形覆盖,我们利用origins索引从原始数据sf$att中取出对应的值,再求和就得到了重叠区域的属性总和
  • 如果你不想加载purrr包,也可以用基础R的sapply实现同样的求和逻辑:
    d$att_sum <- sapply(d$origins, function(idx) sum(sf$att[idx]))
    

运行后结果说明

修改后的结果里,第2个几何区域(重叠区域)的att_sum值会变成2,完全符合你的期望:

Simple feature collection with 3 features and 5 fields
geometry type: POLYGON
dimension: XY
bbox: xmin: 0 ymin: 0 xmax: 1.5 ymax: 1.5
epsg (SRID): NA
proj4string: NA
  att                       geometry n.overlaps origins id att_sum
1   1 POLYGON ((1 0.5, 1 0, 0 0, ...          1       1  1       1
2   1 POLYGON ((0.5 1, 1 1, 1 0.5...          2    1, 2  2       2
3   1 POLYGON ((0.5 1, 0.5 1.5, 1...          1       2  3       1

内容的提问来源于stack exchange,提问作者Paulo E. Cardoso

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:26:23