合并多边形并求和它们的值 [英] Merging polygons and summing their values
问题描述
我有一个包含许多重叠多边形的数据框,我想将它们组合成一个形状,其值等于给定给每个单独多边形的值的总和.
I have a dataframe with many overlapping polygons that I would like to combine into a single shape with the value that equates to the sum of the values given to each infividual polygon.
一些示例数据:
df <- data.frame(x = c(0.5, 1.5, 4.5, 5.5),
y = c(1, 1, 1, 1),
id = c('a', 'b', 'c', 'd'),
score = c(1, 3, 2, 4))
s_df <- SpatialPointsDataFrame(df[, c('x', 'y')], df[, 3:4]) %>%
as('sf') %>%
st_buffer(dist = 1)
plot(s_df)
我可以通过使用 sf 包中的 st_union 函数来获得这些多边形的并集,我认为下一步是在该多边形和原始多边形之间进行空间连接.但是,我不知道该怎么做.
I can get the union of these polygons by using the st_union function in the sf package, and I think the next step would be to do a spatial join between that and the original polygons. However, I cant figure out how to do it.
st_union 提供一个多面对象作为其输出,但 st_intersects 不适用于该对象类,而且我似乎也无法从多面对象创建 SpatialPolygonsDataframe.
st_union gives a multipolygon object as its output, but st_intersects doesn't work with that object class, and I can't seem to make a SpatialPolygonsDataframe from a multipolygon object either.
这是一个如此简单的任务,我觉得一定有一些我忽略或遗漏的基本功能
It is such a simple task I feel like there must be some basic function that I have either overlooked or missed
任何帮助将不胜感激
推荐答案
你考虑过不起眼的 dplyr::summarise()
吗?
Have you considered the humble dplyr::summarise()
?
它将合并您的空间对象的几何图形 - 如果您设置分组变量,则可以合并为单个几何图形或多个几何图形 - 并且它可以进行任何聚合,例如在这个玩具示例中计算总分.
It will merge geometry of your spatial object - either to a single geometry, or multiple ones if you set a grouping variable - and it can do any aggregation, such as calculating total of score in this toy example.
一个可能的分组变量是多边形与其自身的交集——它似乎在这个例子中有效,我希望它能概括
A possible grouping variable is intersection of the polygons with themselves - it seems to work in this example, I hope it will generalise
library(sf)
library(sp)
library(dplyr)
df <- data.frame(x = c(0.5, 1.5, 4.5, 5.5),
y = c(1, 1, 1, 1),
id = c('a', 'b', 'c', 'd'),
score = c(1, 3, 2, 4))
s_df <- SpatialPointsDataFrame(df[, c('x', 'y')], df[, 3:4]) %>%
as('sf') %>%
st_buffer(dist = 1)
plot(s_df)
result <- s_df %>%
group_by(group = paste(st_intersects(s_df, s_df, sparse = T))) %>%
summarise(score = sum(score))
plot(result["score"])
这篇关于合并多边形并求和它们的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!