Add two layers of a raster stack, store result in third layer using terra

Viewed 34

I am trying to use a custom formula on two layers of a raster stack, and update the values in a third layer with the result. Here is my attempt (which does not work):

a <- rast(ncol = 10, nrow = 10)
values(a) <- rep(5,100)
names(a) <- "layer_one"

b <- rast(ncol = 10, nrow = 10)
values(b) <- rep(10,100)
names(b) <- "layer_two"

c <- rast(ncol = 10, nrow = 10)
values(c) <- rep(NA,100)
names(c) <- "layer_three"

z <- c(a,b)

raster_fun <- function(i) { 
      i[[1]] * i[[2]] + 30/10
    }

z[["layer_three"]] <- app(z, raster_fun)

z

class       : SpatRaster 
dimensions  : 10, 10, 2  (nrow, ncol, nlyr)
resolution  : 36, 18  (x, y)
extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 
sources     : memory  
              memory  
names       : layer_one, layer_two 
min values  :         5,        10 
max values  :         5,        10 
1 Answers

That is a bug that has now been fixed in the development version of "terra" (thanks to the report by JimShady). Here is a work-around

z$layer_three <- app(z, raster_fun)
z
#class       : SpatRaster 
#dimensions  : 10, 10, 3  (nrow, ncol, nlyr)
#resolution  : 36, 18  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : lon/lat WGS 84 
#sources     : memory  
#              memory  
#              memory  
#names       : layer_one, layer_two, layer_three 
#min values  :         5,        10,          53 
#max values  :         5,        10,          53 
Related