Search code examples
rrasterr-sp

how to get cell dimensions from rasterized ```SpatialPolygonsDataFrame```?


I have SpatialPolygonsDataFrame class in R, which I want to rasterize. I rasterize the the polygon using this code below:

> p <- shapefile('MadaGranary')
> p
class       : SpatialPolygonsDataFrame 
features    : 1 
extent      : 100.1269, 100.5313, 5.793798, 6.446769  (xmin, xmax, ymin, ymax)
crs         : +proj=longlat +datum=WGS84 +no_defs 
variables   : 1
names       : id 
value       :  1 
> crs(p) <- NULL

> # Define RasterLayer object
> r.raster <- raster(extent(p), res = 100)
> #rasterize
> p.r <- rasterize(p, r.raster)
> print(p.r)
class      : RasterLayer 
dimensions : 1, 1, 1  (nrow, ncol, ncell)
resolution : 100, 100  (x, y)
extent     : 100.1269, 200.1269, -93.55323, 6.446769  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs 
source     : memory
names      : layer 
values     : NA, NA  (min, max)
attributes :
 ID id
  1  1

Unfortunately, this chunk of code has assigned cell dimensions to dimensions : 1, 1, 1 (nrow, ncol, ncell), and its very important for me to get the actual values of ncols and nrows.

And when I print p.r, I need to get the values of dimensions : (nrow, ncol, ncell) in the console so that I will be able to save all attributes in order to use it another analysis later. attention:The resolutionoutput that I need to get should be real values representing ncols and nrow in the new raster, but not just dimensions : 1, 1, 1 (nrow, ncol, ncell) as shown in my code.

Can any one help please??


Solution

  • If you want to set nrow and ncol then you do so (and not set the resolution, which expresses the size of each cell). Here is an example:

    library(raster)
    #Loading required package: sp
    e <- extent(0,1,0,1)
    r <- raster(e, nrow=100, ncol=100)
    r
    #class      : RasterLayer 
    #dimensions : 100, 100, 10000  (nrow, ncol, ncell)
    #resolution : 0.01, 0.01  (x, y)
    #extent     : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
    #crs        : NA