Search code examples
rrasterlayer

How to save a SpatRaster object with different layers and then load it again in R?


I have a raster object ("Climate") made up of different layers/variables ( bio01, bio07, bio08...) Below you can see the details:

class       : SpatRaster 
dimensions  : 98, 174, 8  (nrow, ncol, nlyr)
resolution  : 0.5, 0.5  (x, y)
extent      : -27, 60, 32.5, 81.5  (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 
source(s)   : memory
varnames    : bio01 
              bio07 
              bio08 
              ...
names       :     bio01,     bio07,     bio08,     bio18,    bio14,      lai, ... 
min values  : -36.07298,  4.962311, -6.948818,  125.3619,    0.000, 0.000000, ... 
max values  :  20.01547, 41.839218, 33.729374, 3260.1653, 1559.828, 6.025625, ... 
time (years): -53050 

How could I save "Climate" in my directory and to load it in R with exactly the same format and variable names? If I save it in a .nc format file, when I load it the names of variables are not the same... Thank you


Solution

  • You have not provided any data. So, I am using a default data available with terra R package.

    library(terra)
    #> terra 1.7.18
    
    # Read raster data with multiple layers
    r <-  rast(system.file("ex/logo.tif", package = "terra"))
    r
    #> class       : SpatRaster 
    #> dimensions  : 77, 101, 3  (nrow, ncol, nlyr)
    #> resolution  : 1, 1  (x, y)
    #> extent      : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
    #> coord. ref. : Cartesian (Meter) 
    #> source      : logo.tif 
    #> colors RGB  : 1, 2, 3 
    #> names       : red, green, blue 
    #> min values  :   0,     0,    0 
    #> max values  : 255,   255,  255
    
    #Write the raster data to disk
    writeRaster(r, "test.tif", overwrite = T)
    
    #Read the written raster data
    r1 <- rast("test.tif")
    r1
    #> class       : SpatRaster 
    #> dimensions  : 77, 101, 3  (nrow, ncol, nlyr)
    #> resolution  : 1, 1  (x, y)
    #> extent      : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
    #> coord. ref. : Cartesian (Meter) 
    #> source      : test.tif 
    #> colors RGB  : 1, 2, 3 
    #> names       : red, green, blue 
    #> min values  :   0,     0,    0 
    #> max values  : 255,   255,  255
    

    Created on 2023-05-16 with reprex v2.0.2