Search code examples
rterra

How to overwrite a Raster file in terra


I have a series of scripts where I want to read in a raster, add a new variable, then save the raster again.

However, terra::writeRaster is currently preventing me from overwriting the raster file that I have open. I expected that by setting the argument overwrite = TRUE it would allow me to do this, but I currently get the error: Error: [writeRaster] source and target filename cannot be the same

Is there a workaround for this?

Here is an example of the problem:

library(terra)

x <- rast(ncol=10, nrow=10, nlyr=1)
x <- init(x, "cell")
x <- spatSample(x, ncell(x), "random", as.raster=TRUE)

f <- file.path(tempdir(), "test.tif")
writeRaster(x, f)

y = terra::rast(f)
writeRaster(y, f, overwrite=TRUE)
#Error: [writeRaster] source and target filename cannot be the same

Solution

  • That is not allowed because the program cannot first overwrite the existing file (to write the output to) and then read from it.

    A simple workaround would be to rename the input file

    ftmp <- paste0(tempfile(), ".tif")
    file.rename(f, ftmp)
    r <- rast(ftmp)
    writeRaster(r, f, overwrite=TRUE)
    file.remove(ftmp)
    

    If your raster is not that large, a simpler approach is to first do something that would load the values into memory

    r <- rast(f) + 0
    writeRaster(r, f, overwrite=TRUE)
    

    Perhaps there should be a "toMemory" method for that