Search code examples
rscale

Multiplying raster brick


I have a Rasterbrick of 105 NDVI modis pictures, that I need to multiply by 0.0001 to get the right NDVI scale.

ndvi.crop <- brick("ndvi_crop.grd")
ndvi_corrected <- ndvi.crop * 0.0001

this is my code, I always get several warning for the ndvi_corrected and it takes very long to calculate.

ndvi_corrected <- ndvi.crop * 0.0001
#There were 50 or more warnings (use warnings() to see the first 50)
#warnings()

#1: In for (b in 1:raster@data@nlayers) { ... :
#  closing unused connection 4 (C:\Users\XXX\AppData\Local\Temp\RtmpKad8Tt\raster\r_tmp_2023-07-08_161102_8832_97723.gri)
#2: In writeBin(as.vector(v[start:end, ]), x@file@con, size = x@file@dsize) :
#  problem writing to connection

Also I cannot export it as .grd.

writeRaster(ndvi.crop.sc, file = 'D:/RELA2/ndvi_corrected.grd',
            format = 'raster', overwrite = TRUE,
            options = c('INTERLEAVE=BAND','COMPRESS=LZW'))

Do you have any idea what the problem could be? I have the same problem with my NPP rasterstack


Solution

  • The problem you are encountering that, in this case with a very large raster, the output values need to be written to a temporary file; and your temp folder does not have enough space (or you may be out of disk space more generally).

    You should get a more informative error message when using the modern way to do this (the "raster" package has been replaced by "terra").

    library(terra)
    ndvi.crop <- rast("ndvi_crop.grd")
    ndvi_corrected <- ndvi.crop * 0.0001
    

    Perhaps you can make some space by emptying your temp folder. You can also set it to a folder on another disk that has more space. Something like

    terraOptions(tempdir="d:/temp")
    

    But then you need to remove the files yourself when you are done! (The default folder is removed when the R session ends.)

    You can also avoid writing a temp file by specifying a permanent filename, in this case you could do

    ndvi_corrected <- prod(ndvi.crop, 0.0001, filename="test.tif")