6.5 Rasterization

Vector —> Raster : terra::rasterize()

We are using a data set from spData:

# the easy part
cycle_hire_osm = spData::cycle_hire_osm
cycle_hire_osm_projected = st_transform(cycle_hire_osm, "EPSG:27700")
# The new part: building a raster template
raster_template = terra::rast(ext(cycle_hire_osm_projected), resolution = 1000,
                       crs = st_crs(cycle_hire_osm_projected)$wkt)
  • First Presence/absence:
ch_raster1 = rasterize(cycle_hire_osm_projected, raster_template)
plot(ch_raster1, col = "yellow")

  • Second: count with length :
ch_raster2 = rasterize(cycle_hire_osm_projected, raster_template, 
                       fun = "length")
plot(ch_raster2)

  • Third: sum of a variable
ch_raster3 = terra::rasterize(cycle_hire_osm_projected, raster_template, 
                       field = "capacity", fun = sum, na.rm = TRUE)
plot(ch_raster3)

rasterize() has an argument touches that is useful when dealing with lines or polygon border.