When you project a raster by specifying the CRS as the second argument, the dimensions of the projected raster are determined "automagically" and generally don't correspond to the original raster. This means that the number of cells is different, and the values are obviously not the same.
(Here I'm using a more suitable CRS for Luxembourg that does not distort the geometry)
library(terra)
# sample data in terra package
elev_path <- system.file("ex/elev.tif", package="terra")
elev_source <- rast(elev_path) # in 4326 by default
# use LUREF / Luxembourg TM projection (EPSG:2169)
# https://epsg.io/2169
target_crs <- "epsg:2169"
elev_target <- project(elev_source, target_crs)
# compare source and target
print(elev_source)
print(elev_target)
hist(elev_source)
hist(elev_target)
# not same dimensions, somewhat different values, this is to be expecte
The recommended way of using the project function is to provide a target raster template (dimensions/resolution, extent, and CRS). This will keep the same dimensions; however, the values will generally still differ.
# from the terra::project help page
# if (x is a SpatRaster, the preferred approach is for y to be a SpatRaster as well,
# serving as a template for the geometry (extent and resolution) of the output SpatRaster.
# Alternatively, you can provide a coordinate reference system (CRS) description.
# define target raster template
target_ext <- project(ext(elev_source), from = crs(elev_source), to = target_crs)
rast_template <- rast(nrows = nrow(elev_source), ncols = ncol(elev_source), extent = target_ext, crs = target_crs)
# project using target raster template
elev_target <- project(elev_source, rast_template)
# compare source and target
print(elev_source)
print(elev_target)
old.par <- par(pty = "s")
plot(values(elev_source), values(elev_target), pch = 16, xlab = "source", ylab = "target")
par(old.par)
# same dimensions, somewhat different values, this is to be expected
To keep the exact same values, you can try going through the vector format (polygons). It works in reprex, and hopefully, it will also work with your real data.
# create target raster by going through polygons
# convert to polygons
poly_source <- as.polygons(elev_source, round = FALSE, aggregate = FALSE, na.rm = FALSE)
# project to target CRS
poly_target <- project(poly_source, target_crs)
# convert projected polygons back to raster
elev_target <- rasterize(poly_target, rast_template, field = names(elev_source)[1])
# compare source and target
print(elev_source)
print(elev_target)
old.par <- par(pty = "s")
plot(values(elev_source), values(elev_target), pch = 16, xlab = "source", ylab = "target")
par(old.par)
print(all.equal(values(elev_source), values(elev_target)))
# same dimensions, same values