[英]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.我有一个 dataframe 有许多重叠的多边形,我想将它们组合成一个形状,其值等于赋予每个单独多边形的值的总和。
some example data:一些示例数据:
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)
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.我可以通过使用 sf package 中的 st_union function 来获得这些多边形的联合,我认为下一步是在该多边形和原始多边形之间进行空间连接。 However, I cant figure out how to do it.
但是,我不知道该怎么做。
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. 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这是一个如此简单的任务,我觉得一定有一些基本的 function 被我忽略或错过了
Any help would be greatly appreciated任何帮助将不胜感激
Have you considered the humble dplyr::summarise()
?您是否考虑过不起眼的
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.它将合并您的空间 object 的几何图形 - 如果您设置了分组变量,则可以合并到单个几何图形或多个几何图形 - 它可以进行任何聚合,例如在这个玩具示例中计算总分。
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"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.