Merging polygons and summing their values

女生的网名这么多〃 提交于 2021-02-17 05:47:28

问题


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.

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. 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.

It is such a simple task I feel like there must be some basic function that I have either overlooked or missed

Any help would be greatly appreciated


回答1:


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"])



来源:https://stackoverflow.com/questions/66068003/merging-polygons-and-summing-their-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!