0

I want to multiply two rasters in R with 'terra'. Raster1 has 457 bands with EVI values meanwhile raster2 is a one-layer raster -of almost same extent- with binary values (0 or 1). The result that I want to achieve is to get raster1 (with the 457 original bands) with values only in pixels that has a value = 1 in raster2. That's why I want to multiply them.

I have tried:

result <- raster1 * raster2

result <- overlay(raster1, raster2, fun = function(x,y){return(x*y)}, unstack=FALSE)

But it doesn't work. I appreciate some help.

val
  • 1

1 Answers1

1

Example data (please always include some):

library(terra)
f <- system.file("ex/logo.tif", package="terra")
r1 <- rast(c(f, f))
r2 <- rast(r1, nlyr=1)
set.seed(0)
values(r2) <- sample(c(0,1), ncell(r2), replace=TRUE)

Solution

x <- mask(r1, r2, maskvalue=0)

If you multiply (r1 * r2), all values that are zero in r2 become zero in the output, but you want them to become NA, and that is what mask will do for you.

Alternatively, you could first change the cells that are 0 to NA, and then multiply, but that is unnecessarily convoluted:

m <- subst(r2, 0, NA)
y <- r1 * m 
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63