Search code examples
rgispixelraster

Changing values in a raster


I have a raster file (created in QGIS, from a vectorial file).

I would like to know if it is possible, in R:

1) to change the values of the pixels? (I believe all the cells have the value "1" associated, or at least the blue pixels (check images below), and I don't know the values for the white pixels, but I would like to set it to "2", for instance, so it would be binary)

2) to "crop" the raster?

Here are the characteristics of the input raster:

> catC1raster
class       : RasterLayer 
dimensions  : 1384, 2359, 3264856  (nrow, ncol, ncell)
resolution  : 30, 30  (x, y)
extent      : 325352.8, 396122.8, 4613074, 4654594  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=31 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0 
names       : CAT_C1_30m 

And here is the plot:

enter image description here


Solution

  • To change the NA values (white on your plot) to 2, you can use reclassify

    library(raster)
    x <- reclassify(catC1raster, cbind(NA, 2))
    

    Or, with the terra package use classify

    library(terra)
    x <- classify(catC1raster, cbind(NA, 2))
    

    More info here:

    https://rspatial.org/terra/spatial/8-rastermanip.html