Aligns two sf objects to a common CRS.
Arguments
- a, b
Objects of class sf or sfc.
- prefer
Which object's CRS to keep ("a" or "b").
- target_crs
Optional target CRS to apply to both: anything
sf::st_crs()accepts, including an sf or sfc object, whose CRS is used.- on_transform_error
What to do when st_transform() fails:
"stop"(default) raises an error immediately;"set_crs"falls back to st_set_crs() (UNSAFE: coordinates are NOT reprojected, only the CRS label is overwritten). The"set_crs"option exists only for rare edge cases where you are certain the coordinates already match the target CRS definition.
Details
When one input carries no CRS, the same lon/lat heuristic
ensure_projected() uses decides what happens, so both entry points place
identical data in the same place: coordinates that look like degrees are
taken as EPSG:4326 and reprojected to the other object's CRS (or
target_crs); coordinates that do not are stamped with
sf::st_set_crs(), which relabels without moving them. Either way the
assumption is announced with a warning.
See also
Other spatial data preparation:
clip_target_for(),
coerce_to_points(),
ensure_projected(),
prep_model_data()
Examples
library(sf)
a <- st_as_sf(data.frame(x = c(500000, 500100), y = c(4000000, 4000100)),
coords = c("x", "y"), crs = 32632)
b <- st_transform(a, 4326) # same points, lon/lat
h <- harmonize_crs(a, b) # b is brought into a's CRS
c(a = st_crs(h$a)$epsg, b = st_crs(h$b)$epsg)
#> a b
#> 32632 32632
st_crs(h$a) == st_crs(h$b)
#> [1] TRUE