Search code examples
rterra

Error: external pointer is not valid when saving SpatRasters from the R environment


I am working with a list of SpatRasters using the “terra” package. I have created the list of rasters from a script and I saved the R environment. However, when I load the list of SpatRasters from another script, I encounter the following message error:

Error: external pointer is not valid

Here is a reproducible example:

library(terra)
x <- terra::rast(xmin=-110, xmax=-80, ymin=40, ymax=70, ncols=30, nrows=30)
values(x) <- 1:ncell(x)
r <- c(x, x, x, x)
r <- list(r, r, r, r)
save(r, file = "test.Rdata")

rm(list=ls(all=TRUE))

load("test.Rdata")
r
#[[1]]
#class       : SpatRaster 
#Error: external pointer is not valid

Could you please provide guidance on resolving this issue?  Any help would be appreciated.


Solution

  • You cannot save SpatRaster objects in a ".RData" file. See the fourth paragraph in ?terra

    You should not be using ".RData" files anyway (because it is opaque what happens when you load one); it is much better to use ".rds" files (created with saveRDS).

    That still won't work for a list of SpatRasters, unless you first "wrap" them. You can do

    library(terra)
    x <- terra::rast(xmin=-110, xmax=-80, ymin=40, ymax=70, ncols=30, nrows=30)
    values(x) <- 1:ncell(x)
    r <- c(x, x, x, x)
    r <- list(r, r, r, r)
    
    s <- lapply(r, wrap)
    saveRDS(s, 'wrap.rds')
    
    x <- readRDS("wrap.rds")
    x <- lapply(x, rast)
    

    But the canonical and efficient way to save SpatRasters is with writeRaster. You can also save individual SpatRasters with saveRDS (without explicitly wrapping).