Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

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

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

question from:https://stackoverflow.com/questions/66068003/merging-polygons-and-summing-their-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...