Since you are assigning NA's to the new extent raster then you can use terra::merge
or simplify the workflow and just use terra::extend
library(terra)
or <- rast(ext(-2700100, 2750900, -2500900, 3342100),
resolution = 1000)
or[] <- runif(ncell(or))
extend_cells <- 500
Using terra::extend
original.extend <- extend(or, c(extend_cells,extend_cells))
plot(ext(original.extend), lwd=2, col="red")
plot(original.extend, colNA=NA, add=TRUE)
plot(ext(or), lwd=2, add=TRUE)
nrow(original.extend) - nrow(or)
ncol(original.extend) - ncol(or)
Compared to your method of expanding the extent and then using terra::merge
extended_extent <- c(floor(ext(or)[1]) - extend_cells * res(or)[1],
ceiling(ext(or)[2]) + extend_cells * res(or)[1],
floor(ext(or)[3]) - extend_cells * res(or)[2],
ceiling(ext(or)[4]) + extend_cells * res(or)[2])
# Create a new raster with nodata values
new_raster <- rast(nrow=nrow(or) + extend_cells * 2,
ncol=ncol(or) + extend_cells * 2,
xmin=extended_extent[1], xmax=extended_extent[2],
ymin=extended_extent[3], ymax=extended_extent[4],
crs=crs(or))
new_raster[] <- NA
rextend <- merge(or, new_raster)
plot(ext(rextend), lwd=2, col="red")
plot(rextend, colNA=NA, add=TRUE)
plot(ext(or), lwd=2, add=TRUE)
length(or[is.na(or)])
length(rextend[is.na(rextend)])