Aniruddha Marathe
Aniruddha Marathe

Reputation: 31

Can I 'save' a SpatRaster in a R workspace (RData) file?

I noticed that if I load a raster from a file that is stored on local hard disk, using terra package and then load the workspace later, the SpatRaster object does not have any data associated with it. Is there a way to keep all the information associated with the SpatRaster object while saving and loading the workspace?

Here is a the example code to illustrate the issue:

library(terra)
f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)

#This produces the following output
r
#class       : SpatRaster 
#dimensions  : 90, 95, 1  (nrow, ncol, nlyr)
#resolution  : 0.008333333, 0.008333333  (x, y)
#extent      : 5.741667, 6.533333, 49.44167, 50.19167  (xmin, xmax, 
               ymin, #ymax)
#coord. ref. : lon/lat WGS 84 (EPSG:4326) 
#source      : elev.tif 
#name        : elevation 
#min value   :       141 
#max value   :       547

sources(r)#this works

save.image("delete_if_found.RData")

rm(list = ls())

load("delete_if_found.RData")
r
#which returns the spatraster as

#class       : SpatRaster
#Error in .External(list(name = "CppMethod__invoke_notvoid", address = \<pointer: (nil)\>,  :
#NULL value passed as symbol address`

I am currently importing all the relevant files again after loading the workspace, is there any other way to go about it?

Upvotes: 3

Views: 1618

Answers (2)

Robert Hijmans
Robert Hijmans

Reputation: 47036

You can use writeRaster and then rast and you can also use saveRDS and readRDS, but you cannot use save and load.

As far as I am concerned that is a good thing because saving a session is generally a bad idea (and I wish that R would not prod you to do that). It is bad because you should not start analysis with data coming from nowhere. Instead, you can save your intermediate data to files and read them again in the next step.

Upvotes: 6

Esther
Esther

Reputation: 436

Hello Aniruddha Marathe and welcome to SO!

If you take a look in the terra package documentation, you will see this:

[...] They cannot be recovered from a saved R session either or directly passed to nodes on a computer cluster. Generally, you should use writeRaster to save SpatRaster objects to disk (and pass a filename or cell values to cluster nodes)

So, you will have to load the SpatRaster each time you want to use it by executing terra::rast(system.file("ex/elev.tif", package="terra")), instead of doing it with the load() function.

Hope this helps 😀

Upvotes: 5

Related Questions