library(sf)
# A simple coordinate transformer: scale and shift
scale_shift <- function(coords, sx = 1, sy = 1, dx = 0, dy = 0) {
X <- coords[, 1] * sx + dx
Y <- coords[, 2] * sy + dy
cbind(X, Y)
}
# POINT example
pt <- st_sfc(st_point(c(0, 0)), crs = 3857)
st_transform_custom(pt, transform_fun = scale_shift,
args = list(sx = 2, sy = 2, dx = 1000, dy = -500))
# LINESTRING example
ln <- st_sfc(st_linestring(rbind(c(0, 0), c(1, 0), c(1, 1))), crs = 3857)
st_transform_custom(ln, transform_fun = scale_shift,
args = list(sx = 10, sy = 10))
# POLYGON example (unit square)
poly <- st_sfc(st_polygon(list(rbind(c(0,0), c(1,0), c(1,1),
c(0,1), c(0,0)))), crs = 3857)
st_transform_custom(poly, transform_fun = scale_shift,
args = list(sx = 2, sy = 0.5, dx = 5))
# MULTIPOLYGON example (two disjoint squares)
mp <- st_sfc(st_multipolygon(list(
list(rbind(c(0,0), c(1,0), c(1,1), c(0,1), c(0,0))),
list(rbind(c(2,2), c(3,2), c(3,3), c(2,3), c(2,2)))
)), crs = 3857)
st_transform_custom(mp, transform_fun = scale_shift,
args = list(dx = 100, dy = 100))
# In an sf data frame
sf_df <- st_sf(id = 1:2, geometry = st_sfc(
st_point(c(10, 10)),
st_linestring(rbind(c(0,0), c(2,0), c(2,2)))
), crs = 3857)
st_transform_custom(sf_df, transform_fun = scale_shift,
args = list(sx = 3, sy = 3))
Run the code above in your browser using DataLab