# Intersection of two Raster objects

I have two raster objects r1 (in grey and green) and r2 (in pink) that I want to intersect with R. I tried with the R function `intersect` from the `raster` package but it only intersect the `extent` of the two objects :

## I would like to get a raster object r3 that have the shape of r2 (pink), but the values of r1.

Do you know how I can do this ?

EDIT :

I have a find a solution by firstly insersecting r1 and r2 into r3 then converting r3 and r2 to SpatialPolygonsDataFrame using the `rasterToPolygons`fonction. The intersection of r3 and r2 converted into SpatialPolygonsDataFrame is close to what I wanted to get : • you can build a mask with r2 where pink =1, no-pink=0 (or reclassify); then r3=new-r2*r1. – Pau Feb 19 '15 at 15:02

## 1 Answer

This is exactly what the function `raster::mask(x, mask)` is for. It sets cells in `x` to `NA` when the corresponding cell in `mask` is `NA`.

``````library(sp)
library(raster)

# Create some sample data
r1 <- raster(nrows=40, ncols=40, xmn=0, xmx=2, ymn=0, ymx=2)
r1[] <- seq(1, 100, length.out=ncell(r1))
r2 <- raster(outer(1:20,20:1), xmn=0, xmx=1, ymn=0, ymx=1)
r2 <- reclassify(r2, c(0,100,NA))
`````` The rasters must be of the same resolution and, if they're not the same extent, as is the case in the example I constructed, you should apply crop first.

``````# Bring to the same extent with crop then
# Use mask to set cells in r1 to NA when corresponding r2 cell is NA
r3 <- mask(crop(r1, r2), r2)
`````` This assumes that the part of r2 that you want to remove from r1 is coded as NA/NoData. If not, use `raster::subs()` to make this the case.