Search code examples
rrasterr-rasterterra

resample() function in R's "terra" library does not work properly in specific situation


In the code below, I am trying to resample a high resolution raster into a lower resolution raster using resample(x, y, method = "sum"). However, the resampled raster shows NA on some edges.

library(terra)
set.seed(42)

low_res <- rast(xmin = -1.05, xmax = 1.05, ymin = -0.05, ymax = 2.05, res = 0.5)

high_res <- rast(xmin = -1, xmax = 1, ymin = 0, ymax = 2, res = 0.01)
high_res[] <- runif(ncell(high_res))
plot(high_res, colNA = "darkblue")

resampled <- resample(high_res, low_res, method = "sum")
plot(resampled, colNA = "darkblue")
plot(as.polygons(low_res), add=TRUE, border='black', lwd=1) 

The high resolution raster:

enter image description here

The resampled raster (the dark-blue cells are NAs):

enter image description here

But, if the extent of the low resolution raster rounded (i.e., deleting the _.05), everything looks good:

library(terra)
set.seed(42)

##################################
# only changed extent here
low_res <- rast(xmin = -1, xmax = 1, ymin = -0, ymax = 2, res = 0.5) 
##################################

high_res <- rast(xmin = -1, xmax = 1, ymin = 0, ymax = 2, res = 0.01)
high_res[] <- runif(ncell(high_res))
plot(high_res, colNA = "darkblue")

resampled <- resample(high_res, low_res, method = "sum")
plot(resampled, colNA = "darkblue")
plot(as.polygons(low_res), add=TRUE, border='black', lwd=1) 

The resampled raster:

enter image description here


Solution

  • What you experience is due to a bug in GDAL that has been fixed.

    I do not see the problem (in your first example) with GDAL 3.6

    library(terra)
    gdal()
    #[1] "3.6.0"
    

    Here is a post about GDAL versions with R packages.

    Right now, you can get GDAL version 3.6.2 on windows by installing from source in R-devel and RTools43 and on OSX by installing from source with the current versions of brew.