7.16 Vector to Raster

file <- system.file("gpkg/nc.gpkg", package="sf")
read_sf(file) |> 
  st_geometry() |>
  st_as_stars() |>
  plot(key.pos = 4)

Rasterising existing features is done using st_rasterize

read_sf(file) |>
  dplyr::mutate(name = as.factor(NAME)) |>
  dplyr::select(SID74, SID79, name) |>
  st_rasterize()
## stars object with 2 dimensions and 3 attributes
## attribute(s):
##      SID74            SID79             name       
##  Min.   : 0.000   Min.   : 0.000   Sampson :  655  
##  1st Qu.: 3.000   1st Qu.: 3.000   Columbus:  648  
##  Median : 5.000   Median : 6.000   Robeson :  648  
##  Mean   : 7.892   Mean   : 9.584   Bladen  :  604  
##  3rd Qu.:10.000   3rd Qu.:13.000   Wake    :  590  
##  Max.   :44.000   Max.   :57.000   (Other) :30952  
##  NA's   :30904    NA's   :30904    NA's    :30904  
## dimension(s):
##   from  to offset    delta refsys point x/y
## x    1 461 -84.32  0.01925  NAD27 FALSE [x]
## y    1 141  36.59 -0.01925  NAD27 FALSE [y]

Similarly, line and point geometries can be rasterised

read_sf(file) |>
  st_cast("MULTILINESTRING") |>
  dplyr::select(CNTY_ID) |>
  st_rasterize() |>
  plot(key.pos = 4)