Search code examples
rrasterterra

How to apply a custom function to a SpatRasterDataset in the terra package?


I am trying to apply a custom function to summarize across rasters in a SpatRasterDataset using terra but I am getting the following error. Below is a minimum reproducible error.

#make a spat raster dataset 
r <- rast(ncols=2, nrows=2)
values(r) <- c(1,2,3,4)
x <- c(r, r*2)
sd <- sds(x, x*4)

#function
mean_x <- function(x){mean(x)}

#apply to a SpatRasterDataset
y_mean <- terra::app(x = sd, fun = mean_x)
Error in x@ptr$writeStart(opt, unique(sources)) : 
  Expecting a string vector: [type=list; required=STRSXP].

Eventually, I will use a different function but I can't get app to work across a SpatRasterDataset.


Solution

  • That is a bug. It has been fixed in terra 1.6.31 (the development version) and now I see:

    library(terra)
    #terra 1.6.31
    r <- rast(ncols=2, nrows=2, vals=c(1,2,3,4))
    x <- c(r, r*2)
    sd <- sds(x, x*4)
    
    my_mean <- function(x){mean(x)}
    
    app(sd, fun = my_mean)
    #class       : SpatRaster 
    #dimensions  : 2, 2, 2  (nrow, ncol, nlyr)
    #resolution  : 180, 90  (x, y)
    #extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
    #coord. ref. : lon/lat WGS 84 
    #source(s)   : memory
    #names       : lyr.1, lyr.1 
    #min values  :   2.5,     5 
    #max values  :  10.0,    20 
     
    

    You can install version 1.6.31, in a couple of hours, with

    install.packages('terra', repos='https://rspatial.r-universe.dev')