It is a little bit unclear what you want to do. Anyway you could use raster::stack()
rather than raster::brick()
to store multi-layer raster and saving time. While if you want to store the pointers with little memory usage you could read files as a raster stack or brick and save them as .rds file with saveRDS()
.
library(raster)
s<-stack("tmmn_2020.nc")
b<-brick(s)#this is slow
saveRDS(s,"stack.rds")
saveRDS(b,"brick.rds")
#read back
r <- readRDS("stack.rds")
To reduce file size on disk you can try to compress them while saving. Something similar to
writeRaster(s,"stack.tif",progress='text',option=c('COMPRESS=LWZ'))
writeRaster(b,"brick.tif",progress='text',option=c('COMPRESS=LWZ'))
But when you use compression, the biggest trade-off is extra processing time which is required to uncompress the image, and after uncompressing, the image would still consume the same amount of memory.
In your case, however, it seems to me that the original files are already heavily compressed, I don't think you can do better with the raster package.
There is the new terra
package that implements lots of functionalities of the raster
package, speeding up computation and reducing memory usage, but for your data, I think the best option is to lose some time to convert files to brick and saving as rds file with saveRDS()
. For instance, I've downloaded the "tmmn_2020.nc" file (146 MB), which is a 366 multi-bands raster. Reading it in r with raster::stack()
or terra::rast()
it's instant, and saving the resulting file with saveRDS()
took 0.1 seconds on my PC, resulting in an 8 Kb file (because it is a pointer).
library(terra)
t <- rast("tmmn_2020.nc")
saveRDS(t,"tstack.rds")
t <- readRDS("tstack.rds")