I need to calculate the geographic centroid of different polygons grouped by category. Let me give an example. Let's say we have this sf dataset
library("sf")
nc <- st_read(system.file("/shape/nc.shp", package="sf"))
Let's say we group the different polygons into categories.
df <- data.frame(id=rep(1:10,rep=10))
nc <- cbind(nc,df)
If we plot it, we can see that different polygons belong to different categories. Most importantly, these polygons are not always contiguous.
plot(nc["id"])
I would like to calculate the geographic centroid for each category. One of the options I consider was to dissolve the different polygons first and then compute the centroid. However, since polygons are non-contiguous, this does not work.
p <- nc %>% group_by(id) %>%
summarise(geometry = st_union(geometry)) %>%
ungroup()
Also, if I try the code below, it gives me the centroid of each polygon and not by group
p <- nc %>% group_by(id) %>%
summarise(geometry = st_centroid(geometry),.groups = "keep")
Any idea on how to obtain the centroid by group?