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)
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)
Share
Improve this question
asked Feb 14 at 22:43
katefull06katefull06
2172 silver badges6 bronze badges
2 Answers
Reset to default 4That 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')
A simple assignment in terra
creates a shallow copy, meaning that the original object can be changed if the derived one is edited by a function that makes an in-place change. The solution if you want to avoid that behaviour is to use deepcopy
. The documentation of deepcopy
shows a similar behaviour for set.ext()
as you discovered for ext()
: https://rspatial.github.io/terra/reference/deepcopy.html
Edit: note the answer by @Robert Hijmans saying that the dev
version of terra
now behaves differently, without the need of a deepcopy