I am working with 2 raster::stack (RS1 and RS2) of 2 equal time series. I need to create a third raster (RS3) which is the result of the pixel by pixel criterion -> if: RS1 > RS2 then RS1, else RS2.
I tried with ifelse unsuccessfully:
RS3 <-ifelse(RS1[] > RS2[], RS1[], RS2[])
I don't know how to go from here.
Example data and using "terra" instead of the (obsolete) "raster" package.
library(terra)
r <- rast(system.file("ex/elev.tif", package="terra"))
x <- c(r, r/2, r*2)
y <- c(r/2, r*2, r)
Solution:
z <- max(x, y)
min and max values:
minmax(x)
# elevation elevation elevation
#min 141 70.5 282
#max 547 273.5 1094
minmax(y)
# elevation elevation elevation
#min 70.5 282 141
#max 273.5 1094 547
minmax(z)
# elevation elevation elevation
#min 141 282 282
#max 547 1094 1094
For more complex functions than max
, that are not "built-in", you can use lapp
like this
zz <- lapp(sds(x, y), pmax)