This is truly bizarre behavior I can't explain.
library(terra)
r1 = rast(nrow = 2, ncol = 2)
values(r1) = c(0, 1, 2, 3)
r2 = r1
ext(r2) = ext(r2)/2
ext(r2)
ext(r1)
What you see is that the extent of 'r1' has also been cut in half. Whyyyyyyy??? By the way, you can change the values of 'r2' without affecting the values of 'r1'. As far as I can tell it only applies to the extent.
This also doesn't happen when doing the same process using the 'raster' package.
library(raster)
r1 = raster(nrow = 2, ncol = 2)
values(r1) = c(0, 1, 2, 3)
r2 = r1
extent(r2) = extent(r2)/2
extent(r2)
extent(r1)
That is a bug that has now been fixed in the development version.
Here is a work-around with as.vector()
:
library(terra)
r1 = rast(nrow = 2, ncol = 2)
values(r1) = c(0, 1, 2, 3)
r2 = r1
ext(r2) = as.vector(ext(r2)/2)
ext(r2)
#SpatExtent : -90, 90, -45, 45 (xmin, xmax, ymin, ymax)
ext(r1)
#SpatExtent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
And with the development version it works as expected
library(terra)
#terra 1.8.24
r1 = rast(nrow = 2, ncol = 2)
values(r1) = c(0, 1, 2, 3)
r2 = r1
ext(r2) = ext(r2)/2
ext(r2)
#SpatExtent : -90, 90, -45, 45 (xmin, xmax, ymin, ymax)
ext(r1)
#SpatExtent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
You can install the development version with
install.packages('terra', repos='https://rspatial.r-universe.dev')