Raster Manipulation – Changing NA Cell Values in a Raster Using Geographic Subset as Condition

rraster

I would like to replace the NA cells that are within a specified extent (here rectangular area defined by drawExtent in the code bellow) of a raster object. My idea was to use the functions cellsFromExtent and extract to extract the NA cells within an extent of the raster and to assign the value 250 to these cells. Finally, the NA cells of the raster that are within the extent should have the value 250 and the other NA cells that are outside the extent would keep the value NA. So, How can I change the values of NA cells in a raster object by using a geographic subset of the raster as a condition ? Here is the beginning of a code:

r <- raster(ncol=10, nrow=10) 
values(r) <- sample(1:8,ncell(r),replace=T)
r[c(5)] <- NA
r[c(20)] <- NA
r[c(43)] <- NA
plot(r)

e <- drawExtent()
z <- extract(r, cellsFromExtent(r, e))

From z, how can I assign the value 250 to the NA cells in the raster (I tested r[is.na(z)] <- 250 but this doesn't work) ?

Best Answer

You were on the right track with cellsFromExtent. Rather than extract you can use the function to return the cell index associated with the extent.

Add library and create data

library(raster)
r <- raster(ncol=10, nrow=10) 
values(r) <- sample(1:8,ncell(r),replace=T)
r[c(5,20,43)] <- NA

Create extent object and plot. I used defined extent but you can still use drawExtent.

e <- extent(-107.1856, 19.31142, -1.197642, 87.12573)
plot(r)
plot(e, add=TRUE)

Here we get a index value for the NA values in the extent then, use the index to replace the values in the entire raster.

( na.idx <- which(r[cellsFromExtent(r, e)] %in% NA) )
r[cellsFromExtent(r, e)[na.idx]] <- 250

plot(r)
plot(e, add=TRUE)