Search code examples
roverlayraster

Replace a value in a raster with the value from another raster


In the following example, I am trying to replace the value 10 in raster r with the respective pixel value from raster r2:

library(raster)    

r <- raster(nrows=25, ncols=25, vals=round(rnorm(625, 3), 0)) #land-use/cover raster
r[ r > 2 ] <- NA
r[ r < 1 ] <- 10
plot(r)

r2 <- raster(nrows=25, ncols=25, vals=round(rnorm(625, 3), 0)) #land-use/cover raster
plot(r2)

I was hoping the following code would work:

r3 <- overlay(r, r2, fun = function(x, y) { x[ x == 10 ] <- y ; return(x) })

... but it returns an error:

Error in (function (x, fun, filename = "", recycle = TRUE, forcefun = FALSE, : cannot use this formula, probably because it is not vectorized

I am sure part of the problem is with "<- y" in the overlay function. I tried using "<- y[ x == 10 ]" instead but I still run into the same problem... Any ideas? Thanks in advance.


Solution

  • If you're using random values for your example, I would suggest to also use a random seed so it's reproducible and comparable.

    Since your two rasters have the same dimensions, you can just use logical indexing.

    Here's a small example:

    library(raster)
    
    set.seed(42)
    
    r <-setValues(raster(ncol=10,nrow=10),round(runif(100,1,10)))
    r2 <-setValues(raster(ncol=10,nrow=10),round(runif(100,1,10)))
    
    # create logical index (for later comparison)
    ix <- r == 10
    
    # returns FALSE, so r2 doesn't have any 10 where r has one
    any(r[ix] == r2[ix])
    
    r[ix] <- r2[ix]
    
    # prints TRUE, so all values have been correctly replaced
    all(r[ix] == r2[ix])
    

    You can do the replacement also in a simple one liner:

    r[r == 10] <- r2[r == 10]
    

    (Edit: Thanks @Nemesi)