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

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) ?

  • 1
    It is not clear as to what you are after. Do you want to define an extent and turn the cells corresponding with the extent to NA values? What does the application of the extract and cellsFromExtent functions have to do with your question? Mar 19, 2016 at 18:15
  • Thanks a lot Jeffrey. I have added some detail in the question.
    – Nell
    Mar 19, 2016 at 20:11

1 Answer 1


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

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(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(e, add=TRUE)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.