How to move polygon to new center in R

Viewed 26

I'm looking for a quick way to move around my polygons in R... I'd like to move the my polygon based on it's center to a new center.

library(sf)
library(ggplot2)

theta <- (0:6) * pi / 3
hexagon <- data.frame(
  x = sin(theta),
  y = cos(theta))

poly <- hexagon %>%
  st_as_sf(coords = c("x", "y")) %>% 
  mutate(geometry = st_combine(geometry))%>%
  st_cast("POLYGON")

How can I move the polygon to the new center (here: red point)?

poly %>%
  ggplot()+
  geom_sf()+
  geom_point(data=data.frame(x=10, y=10), aes(x, y), color="red")

example of ggplot

Thanks!

1 Answers

What you describe is an affine transformation of type shift.

You can perform it by adding a point geometry to your polygon geometry (this works only for geometries, i.e. sfc objects, not full sf data frames with data).

It is safe to do for projected (planar) coordinate reference systems, might be messy for unprojected (lat-long) CRS. See this answer on our sister site, and the comment to it: https://gis.stackexchange.com/questions/437695/move-points-to-different-location/437699#437699

And because an example is more than 100 words:

library(sf)
library(dplyr)
library(ggplot2)

theta <- (0:6) * pi / 3
hexagon <- data.frame(
  x = sin(theta),
  y = cos(theta))

poly <- hexagon %>%
  st_as_sf(coords = c("x", "y")) %>% 
  mutate(geometry = st_combine(geometry))%>%
  st_cast("POLYGON")

poly %>%
  ggplot()+
  geom_sf()+
  geom_point(data=data.frame(x=10, y=10), aes(x, y), color="red")

# the interesting part starts here:

# reframe your red point as an sf object
red_point <- data.frame(x=10, y=10) %>% 
  st_as_sf(coords = c("x", "y"))

# add the two geometries together (just the geometry columns!)
shifted_poly <- poly$geometry + red_point$geometry

# a visual check
ggplot() +
  geom_sf(data = poly) +
  geom_sf(data = shifted_poly) +
  geom_sf(data = red_point, col = "red")

enter image description here

Related