Search code examples
rmatrixraster

How to present some regions in raster (matrix) with conditions from another raster?


I have two matrix r and r2. I would like to plot r , this simply can be done using

       plot (r)

But I would like to mark all values higher than 20 in r2 in the plot of r. a reproducible example:

   library(raster)
  r <- raster(nrows=10, ncols=10)
  r <- setValues(r, 1:ncell(r))
  r2 <- raster(nrows=10, ncols=10)
 r2 <- setValues(r2, 1:ncell(r))
 plot(r)

This will poroduce this:

enter image description here

I would like to mark in this plot all areas where r2 higher than 20 in red for example.Thanks for your ideas


Solution

  • You can do this for example:

    set.seed(1)
    library(raster)
    r <- raster(nrows=5, ncols=5)
    r <- setValues(r, 1:ncell(r))
    r2 <- raster(nrows=5, ncols=5)
    r2 <- setValues(r2, round(runif(ncell(r),10,20)),2)
    ## 100 here as a value that don't exist in range of values(r)
    ## and it gives the blue value
    r[r2<15] <- '100'
    ## I plot the 3 to see check the result
    plot(stack(r,r2,r2<15))
    

    enter image description here