1

I have a simple question about app() family function

I want to divide a vector (of n values) by a raster and to get n resulting rasters

s <- rast(system.file("ex/logo.tif", package="terra"))[[1]] 

lapp(s, aa = c(1, 10, 100, 1000), function(x, aa){0.46 * aa/(x + 1)})

The same would like to know to be done with a SpatRasterDataset. Is that possible?

Here is an example:

fun = function(i, j) { 
    v <- c(1, 10, 100, 1000)
    f <- i + j
    v / f
}
srd <- sds(list(i = s, j = s/10))
r <- lapp(srd, fun = fun, recursive = TRUE )
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
Marcos
  • 31
  • 6

1 Answers1

1

You can do (using a slightly modified example to make it easier to see what happens):

library(terra)
s <- rast(ncols=10, nrows=10)
s <- init(s, 1:10)
v <- c(1, 10, 100, 1000)    
a <- app(s, function(x, aa){ sapply(aa, function(i) 2 * i/x) }, aa=v)
a
#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. : +proj=longlat +datum=WGS84 +no_defs 
#source      : memory 
#names       : lyr.1, lyr.2, lyr.3 
#min values  :   0.2,   2.0,  20.0 
#max values  :     2,    20,   200 

With terra version 1.3-17 (currently the development version), you can now also do:

b <- 2 * v/s

to get the same results. The layers of a SpatRaster are recycled when doing arithmetic with a vector that is longer than the number of layers.

With a SpatRasterDataSet you can do something like the below. It is important to test fun outside of lapp to see if the number of values returned, and their order, make sense.

fun = function(i, j) { 
    v <- c(1, 10, 100, 1000)
    f <- i + j
    f <- rep(f, each=length(v))
    matrix(v / f, ncol=length(v), byrow=TRUE)
}
srd <- sds(list(i = s, j = s/10))
r <- lapp(srd, fun = fun)
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
  • Is this an example or should I ask another question?; ``` fun = function(i, j) { v <- c(1, 10, 100, 1000); o = j/(1 + j); f = i * o; r1 = 0.5 * v/(f + 1); return(r1); }; srd <- sds(i = s, j = s/10); funResult <- lapp(srd, fun = fun, recursive = TRUE ) ``` – Marcos Jul 26 '21 at 13:07
  • This is not what comments are for. I have edited your question for you – Robert Hijmans Jul 26 '21 at 21:08