terrarasterizing

How do I convert a polygon to a raster so that the pixels are the same as the polgons


I have the following shape file and I want to convert the polygons into raster with pixels.

How do I do that so that the pixels have the same resolution (size) as the polygons (or close to it)?

library(terra)
TKshape <- vect("/TK_25_shape_crs_wgs84.shp")

TKshape

class       : SpatVector 
 geometry    : polygons 
 dimensions  : 1240, 19  (geometries, attributes)
 extent      : 7.499192, 10.49876, 47.49912, 49.79888  (xmin, xmax, ymin, ymax)
 source      : TK_25_shape_crs_wgs84.shp
 coord. ref. : lon/lat WGS 84 (EPSG:4326) 
 names       : OBJECTID OBJECT_ID   NAME RECHTSWERT  HOCHWERT  MER_LU_X  MER_LU_Y  MER_RU_X  MER_RU_Y  MER_LO_X (and 9 more)
 type        :    <int>     <num>  <chr>      <num>     <num>     <num>     <num>     <num>     <num>     <num>             
 values      :      505       515 7313SO  4.232e+05 5.386e+06 4.201e+05 5.383e+06 4.262e+05 5.383e+06 4.201e+05             
                    506       516 7313SW   4.17e+05 5.386e+06 4.139e+05 5.384e+06 4.201e+05 5.383e+06  4.14e+05             
                    507       517 7314NO  4.355e+05 5.392e+06 4.324e+05 5.389e+06 4.386e+05 5.389e+06 4.325e+05    

It should be possible with

rr <-rasterize(TKshape, r, "name")

But how do I create the right raster object to match my polygon?


Solution

  • I found the answer to my problem.

    To use rasterize i needed ncol and nrow for the new raster which was the count of the polygons horizontaly and verticaly. So I counted :)

    r <- rast(TKshape, ncols=34, nrows=46)
    temp <- rasterize(TKshape, r)
    
    plot(TKshape)
    

    TKshape

    plot(temp)
    

    temp