# Compare two rasters in R with the cell value from one replacing the cell value from another

I am trying to create a single raster from two rasters. The first raster is made up of all 0 values and the second is made up of the current date value (formatted in days from 001 to 365). The problem is using raster overlay I am struggling to get the result I am after. I can combine the to using the following without any issue:

``````zeroRaster <- overlay(changeDate, zeroRaster, fun=function(x,y){return(x+y)})
``````

however when a specific cell changes multiple times the two dates are added together which is obviously incorrect (with the x+y function being to blame).

As I am struggling to explain I will try and visually represent what I am trying to achieve below: Essentially I just want to replace any cell value in raster y with the new date value from raster x without performing any mathematical functions.

• I am uncertain on your 'changeDate', but can't you just use maximum? That way, you will get the highest number, which matches your example. Of course, if you have multiple years and so on may cause issues, but it all depends on your formatting. – Mikkel Lydholm Rasmussen Jun 17 '15 at 16:47

Here is what Mikkel suggested (use of `max`)

``````library(raster)
cell100 <- raster(nr=3, nc=3, vals=c(100,0,0,0,100,0,0,0,100))
cell101 <- raster(nr=3, nc=3, vals=c(0,0,101,0,101,0,101,0,0))
r <- max(cell100, cell101)

as.matrix(r)
#     [,1] [,2] [,3]
#[1,]  100    0  101
#[2,]    0  101    0
#[3,]  101    0  100
``````

Another (more complex) approach could be

``````cell100 <- raster(nr=3, nc=3, vals=c(100,NA,NA,NA,100,NA,NA,NA,100))
cell101 <- raster(nr=3, nc=3, vals=c(NA,NA,101,NA,101,NA,101,NA,NA))
x <- cell101
x <- cover(x, cell100)
x <- reclassify(x, cbind(NA, 0))
``````