5.8 Rotate

# get centroids
nz_centroid_sfc = st_centroid(nz_sfc)

rotation = function(a){
  r = a * pi / 180 #degrees to radians
  matrix(c(cos(r), sin(r), -sin(r), cos(r)), nrow = 2, ncol = 2)
} 

# rotate by 30 degrees
nz_rotate_sfc = (nz_sfc - nz_centroid_sfc) * rotation(30) + nz_centroid_sfc

nz_rotate_sf = st_set_geometry(nz, nz_rotate_sfc) #return to sf type
st_crs(nz_rotate_sf) <- st_crs(nz) #ensure same coordinate system
nz |>
  ggplot() +
  geom_sf() +
  geom_sf(fill = "green", alpha = 0.5,
          data = nz_rotate_sf) +
  labs(title = "New Zealand",
       subtitle = "Affine Transformation: Rotate",
       caption = "GeoComputation with R book club") +
  theme_minimal()

Rotate