# Changing raster values in specific zone only

I would like to replace raster values only in specific zone of the raster. Say this is my example raster:

``````library(raster)
r <- raster(ncol=1000, nrow=1000)
r[] <- runif(ncell(r),0,1)
extent(r) <- matrix(c(0, 0, 1000, 1000), nrow=2)
``````

What I would like to do now, is to change all values that equal to `val <- 0.8`and replace with `valnew <- 0.2`. The extent of raster where my function should search and replace values is following (only this square of raster should be searched for `val` values in raster and replaced with `newval`)

``````extentnewvals <- matrix(c(300, 300, 500, 500), nrow=2)
``````

Any ideas how to approach it?

I will present a workaround with two pairs of brackets, maybe there is another method more efficient. I rounded values to make this example easiest. Use the first pair of brackets to select values inside the specific extent and the second pair of brackets to change the desired values. Check histogram and plot to view differences:

``````library(raster)

r <- raster(ncol=1000, nrow=1000)
r[] <- round(runif(ncell(r),0,1),1)
extent(r) <- matrix(c(0, 0, 1000, 1000), nrow=2)

extentnewvals <- extent(matrix(c(300, 300, 500, 500), nrow=2))

hist(r)
``````

``````plot(r)
``````

``````# Change values
r[extentnewvals][r[extentnewvals] == 0.8] <- 0.2

hist(r)
``````

``````plot(r)
``````

• this is fantastic! Now.... what if I have NA (instead of 0.2) in cells that I would like to replace?
– MIH
May 2 '18 at 14:18
• I sorted it: r[extentnewvals][is.na(r[extentnewvals])] <- 0.02
– MIH
May 2 '18 at 15:01
• @MIH Exactly! Is the same approach May 2 '18 at 15:24
• any idea how to replace values with nearest neighbours values within the window? say i have NA values: `r[r==0.8] <- NA` or shall i ask new question?
– MIH
May 2 '18 at 15:42
• I prepared new question if you know the answer: gis.stackexchange.com/questions/281582/…
– MIH
May 2 '18 at 15:50