Search code examples
rraster

How to compute the area or number of pixels for selected region in R?


I am drawing a region over a raster files but I need to know how many pixels are covered in this box (by means the area): the raster file is 1440 pixels*720 lines``(25km*25km).

example:

   saf <- stack(system.file("external/rlogo.grd", package="raster")) 
    plotRGB( saf )
    e <- drawExtent()

So after this I drew e as a box but how many pixels/how much is the area? Thanks


Solution

  • Try using raster::crop...

    crop(saf , e )
    #class       : RasterBrick 
    #dimensions  : 40, 50, 2000, 3  (nrow, ncol, ncell, nlayers)
    #resolution  : 1, 1  (x, y)
    #extent      : 23, 73, 26, 66  (xmin, xmax, ymin, ymax)
    #coord. ref. : +proj=merc 
    #data source : in memory
    #names       : red, green, blue 
    #min values  :   0,     0,    0 
    #max values  : 255,   255,  255
    

    And if you just want the number of cells...

    ncell( crop(saf , e ) )
    #[1] 2000
    

    And to eliminate NA....

    x <- crop( saf , e )
    ncell( ! is.na(x[]) )