[GIS] Deleting values from raster layer using R

rraster

I am looking for a way to delete values in my raster layer in R programming. Assume I have a raster layer with the following unique values:

0,1,2,3,4. minimum is 0 and maximum is 4.

How do I delete all values of 0 from my raster layer to remain with the following unique values?

1,2,3,4

Best Answer

It will be relatively easy to change a cell value. Just use the missing value NA to replace the 0. Sometimes, a special number indicates missing value in a raster (such as -999 or any obvious value that will be outside the range of the normal dataset you are working with). For illustration, the code below would change raster of value 0 to NA. The thing to remember is, rasters are just data in a table that has spatial information.

library(raster)

#creation of an empty raster with 100x100 pixel
r <- raster(ncol=100, nrow=100)

#randomly assign 0,1,2,3 or 4 
for (i in 1:100){

  for(j in 1:100){
    r[i,j] <- sample(0:4,1,T)
  }

}

#now replace all 0 with NA
r[r==0] <- NA