Search code examples
rraster

Extract ncell from RasterLayer in R


Suppose I have the following RasterLayer named newTemplate:

class      : RasterLayer 
dimensions : 139615, 184156, 25710939940  (nrow, ncol, ncell)
resolution : 50, 50  (x, y)
extent     : 668395.5, 9876195, 2620826, 9601576  (xmin, xmax, ymin, ymax)
crs        : +proj=utm +zone=17 +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 

From this, i would like to extract the value corresponding to ncell directly i.e. not through the multiplication of nrow and ncol. How would I do this? The reason being is that this indirect method returns the following warning message in R:

[1] NA
Warning message:
In newTemplate@ncols * newTemplate@nrows : NAs produced by integer overflow

Solution

  • You want to get the number of cells from a RasterLayer object?

    There's a function for that: ncell

    library(raster)
    r <- raster()
    
    > print(r)
    class      : RasterLayer 
    dimensions : 180, 360, 64800  (nrow, ncol, ncell)
    resolution : 1, 1  (x, y)
    extent     : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
    crs        : +proj=longlat +datum=WGS84 +no_defs 
    
    > ncell(r)
    [1] 64800