5.4 Raster-vector interactions

This section focuses on interactions between raster and vector geographic data models, introduced in Chapter 2.It includes four main techniques:raster cropping and masking using vector objects (Section 5.4.1);extracting raster values using different types of vector data (Section 5.4.2);and raster-vector conversion (Sections 5.4.3 and 5.4.4).The above concepts are demonstrated using data used in previous chapters to understand their potential real-world applications.

5.4.1 Raster cropping

Many geographic data projects involve integrating data from many different sources, such as remote sensing images (rasters) and administrative boundaries (vectors).Often the extent of input raster datasets is larger than the area of interest.In this case raster cropping and masking are useful for unifying the spatial extent of input data.Both operations reduce object memory use and associated computational resources for subsequent analysis steps, and may be a necessary preprocessing step before creating attractive maps involving raster data.

We will use two objects to illustrate raster cropping:

  • A raster object srtm representing elevation (meters above sea level) in south-western Utah.
  • A vector (sf) object zion representing Zion National Park.
    Both target and cropping objects must have the same projection.The following code chunk therefore not only loads the datasets, from the spDataLarge package installed in Chapter 2,it also reprojects zion (see Section 6 for more on reprojection):
  1. srtm = raster(system.file("raster/srtm.tif", package = "spDataLarge"))
  2. zion = st_read(system.file("vector/zion.gpkg", package = "spDataLarge"))
  3. zion = st_transform(zion, projection(srtm))

We will use crop() from the raster package to crop the srtm raster.crop() reduces the rectangular extent of the object passed to its first argument based on the extent of the object passed to its second argument, as demonstrated in the command below (which generates Figure 5.17(B) — note the smaller extent of the raster background):

  1. srtm_cropped = crop(srtm, zion)

Related to crop() is the raster function mask(), which sets values outside of the bounds of the object passed to its second argument to NA.The following command therefore masks every cell outside of the Zion National Park boundaries (Figure 5.17(C)):

  1. srtm_masked = mask(srtm, zion)

Changing the settings of mask() yields different results.Setting maskvalue = 0, for example, will set all pixels outside the national park to 0.Setting inverse = TRUE will mask everything inside the bounds of the park (see ?mask for details) (Figure 5.17(D)).

  1. srtm_inv_masked = mask(srtm, zion, inverse = TRUE)

Illustration of raster cropping and raster masking.
Figure 5.17: Illustration of raster cropping and raster masking.

5.4.2 Raster extraction

Raster extraction is the process of identifying and returning the values associated with a ‘target’ raster at specific locations, based on a (typically vector) geographic ‘selector’ object.The results depend on the type of selector used (points, lines or polygons) and arguments passed to the raster::extract() function, which we use to demonstrate raster extraction.The reverse of raster extraction — assigning raster cell values based on vector objects — is rasterization, described in Section 5.4.3.

The simplest example is extracting the value of a raster cell at specific points.For this purpose, we will use zion_points, which contain a sample of 30 locations within the Zion National Park (Figure 5.18).The following command extracts elevation values from srtm and assigns the resulting vector to a new column (elevation) in the zion_points dataset:

  1. data("zion_points", package = "spDataLarge")
  2. zion_points$elevation = raster::extract(srtm, zion_points)

The buffer argument can be used to specify a buffer radius (in meters) around each point.The result of raster::extract(srtm, zion_points, buffer = 1000), for example, is a list of vectors, each of which representing the values of cells inside the buffer associated with each point.In practice, this example is a special case of extraction with a polygon selector, described below.

Locations of points used for raster extraction.
Figure 5.18: Locations of points used for raster extraction.

Raster extraction also works with line selectors.To demonstrate this, the code below creates zion_transect, a straight line going from northwest to southeast of the Zion National Park, illustrated in Figure 5.19(A) (see Section 2.2 for a recap on the vector data model):

  1. zion_transect = cbind(c(-113.2, -112.9), c(37.45, 37.2)) %>%
  2. st_linestring() %>%
  3. st_sfc(crs = projection(srtm)) %>%
  4. st_sf()

The utility of extracting heights from a linear selector is illustrated by imagining that you are planning a hike.The method demonstrated below provides an ‘elevation profile’ of the route (the line does not need to be straight), useful for estimating how long it will take due to long climbs:

  1. transect = raster::extract(srtm, zion_transect,
  2. along = TRUE, cellnumbers = TRUE)

Note the use of along = TRUE and cellnumbers = TRUE arguments to return cell IDs along the path.The result is a list containing a matrix of cell IDs in the first column and elevation values in the second.The number of list elements is equal to the number of lines or polygons from which we are extracting values.The subsequent code chunk first converts this tricky matrix-in-a-list object into a simple data frame, returns the coordinates associated with each extracted cell, and finds the associated distances along the transect (see ?geosphere::distGeo() for details):

  1. transect_df = purrr::map_dfr(transect, as_data_frame, .id = "ID")
  2. transect_coords = xyFromCell(srtm, transect_df$cell)
  3. transect_df$dist = c(0, cumsum(geosphere::distGeo(transect_coords)))

The resulting transect_df can be used to create elevation profiles, as illustrated in Figure 5.19(B).

Location of a line used for raster extraction (left) and the elevation along this line (right).
Figure 5.19: Location of a line used for raster extraction (left) and the elevation along this line (right).

The final type of geographic vector object for raster extraction is polygons.Like lines and buffers, polygons tend to return many raster values per polygon.This is demonstrated in the command below, which results in a data frame with column names ID (the row number of the polygon) and srtm (associated elevation values):

  1. zion_srtm_values = raster::extract(x = srtm, y = zion, df = TRUE)

Such results can be used to generate summary statistics for raster values per polygon, for example to characterize a single region or to compare many regions.The generation of summary statistics is demonstrated in the code below, which creates the object zion_srtm_df containing summary statistics for elevation values in Zion National Park (see Figure 5.20(A)):

  1. group_by(zion_srtm_values, ID) %>%
  2. summarize_at(vars(srtm), list(~min, ~mean, ~max))
  3. #> # A tibble: 1 x 4
  4. #> ID min mean max
  5. #> <dbl> <dbl> <dbl> <dbl>
  6. #> 1 1 1122 1818. 2661

The preceding code chunk used the tidyverse to provide summary statistics for cell values per polygon ID, as described in Chapter 3.The results provide useful summaries, for example that the maximum height in the park is around 2,661 meters (other summary statistics, such as standard deviation, can also be calculated in this way).Because there is only one polygon in the example a data frame with a single row is returned; however, the method works when multiple selector polygons are used.

The same approach works for counting occurrences of categorical raster values within polygons.This is illustrated with a land cover dataset (nlcd) from the spDataLarge package in Figure 5.20(B), and demonstrated in the code below:

  1. zion_nlcd = raster::extract(nlcd, zion, df = TRUE, factors = TRUE)
  2. dplyr::select(zion_nlcd, ID, levels) %>%
  3. tidyr::gather(key, value, -ID) %>%
  4. group_by(ID, key, value) %>%
  5. tally() %>%
  6. tidyr::spread(value, n, fill = 0)
  7. #> # A tibble: 1 x 9
  8. #> # Groups: ID, key [1]
  9. #> ID key Barren Cultivated Developed Forest Herbaceous Shrubland
  10. #> <dbl> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
  11. #> 1 1 leve… 98285 62 4205 298299 235 203701
  12. #> # … with 1 more variable: Wetlands <dbl>

Area used for continuous (left) and categorical (right) raster extraction.
Figure 5.20: Area used for continuous (left) and categorical (right) raster extraction.

So far, we have seen how raster::extract() is a flexible way of extracting raster cell values from a range of input geographic objects.An issue with the function, however, is that it is relatively slow.If this is a problem, it is useful to know about alternatives and work-arounds, three of which are presented below.

  • Parallelization: this approach works when using many geographic vector selector objects by splitting them into groups and extracting cell values independently for each group (see ?raster::clusterR() for details of this approach).
  • Use the velox package (Hunziker 2017), which provides a fast method for extracting raster data that fits in memory (see the packages extract vignette for details).
  • Using R-GIS bridges (see Chapter 9): efficient calculation of raster statistics from polygons can be found in the SAGA function saga:gridstatisticsforpolygons, for example, which can be accessed via RQGIS.

5.4.3 Rasterization

Rasterization is the conversion of vector objects into their representation in raster objects.Usually, the output raster is used for quantitative analysis (e.g., analysis of terrain) or modeling.As we saw in Chapter 2 the raster data model has some characteristics that make it conducive to certain methods.Furthermore, the process of rasterization can help simplify datasets because the resulting values all have the same spatial resolution: rasterization can be seen as a special type of geographic data aggregation.

The raster package contains the function rasterize() for doing this work.Its first two arguments are, x, vector object to be rasterized and, y, a ‘template raster’ object defining the extent, resolution and CRS of the output.The geographic resolution of the input raster has a major impact on the results: if it is too low (cell size is too large), the result may miss the full geographic variability of the vector data; if it is too high, computational times may be excessive.There are no simple rules to follow when deciding an appropriate geographic resolution, which is heavily dependent on the intended use of the results.Often the target resolution is imposed on the user, for example when the output of rasterization needs to be aligned to the existing raster.

To demonstrate rasterization in action, we will use a template raster that has the same extent and CRS as the input vector data cycle_hire_osm_projected (a dataset on cycle hire points in London is illustrated in Figure 5.21(A)) and spatial resolution of 1000 meters:

  1. cycle_hire_osm_projected = st_transform(cycle_hire_osm, 27700)
  2. raster_template = raster(extent(cycle_hire_osm_projected), resolution = 1000,
  3. crs = st_crs(cycle_hire_osm_projected)$proj4string)

Rasterization is a very flexible operation: the results depend not only on the nature of the template raster, but also on the type of input vector (e.g., points, polygons) and a variety of arguments taken by the rasterize() function.

To illustrate this flexibility we will try three different approaches to rasterization.First, we create a raster representing the presence or absence of cycle hire points (known as presence/absence rasters).In this case rasterize() requires only one argument in addition to x and y (the aforementioned vector and raster objects): a value to be transferred to all non-empty cells specified by field (results illustrated Figure 5.21(B)).

  1. ch_raster1 = rasterize(cycle_hire_osm_projected, raster_template, field = 1)

The fun argument specifies summary statistics used to convert multiple observations in close proximity into associate cells in the raster object.By default fun = "last" is used but other options such as fun = "count" can be used, in this case to count the number of cycle hire points in each grid cell (the results of this operation are illustrated in Figure 5.21(C)).

  1. ch_raster2 = rasterize(cycle_hire_osm_projected, raster_template,
  2. field = 1, fun = "count")

The new output, ch_raster2, shows the number of cycle hire points in each grid cell.The cycle hire locations have different numbers of bicycles described by the capacity variable, raising the question, what’s the capacity in each grid cell?To calculate that we must sum the field ("capacity"), resulting in output illustrated in Figure 5.21(D), calculated with the following command (other summary functions such as mean could be used):

  1. ch_raster3 = rasterize(cycle_hire_osm_projected, raster_template,
  2. field = "capacity", fun = sum)

Examples of point rasterization.
Figure 5.21: Examples of point rasterization.

Another dataset based on California’s polygons and borders (created below) illustrates rasterization of lines.After casting the polygon objects into a multilinestring, a template raster is created with a resolution of a 0.5 degree:

  1. california = dplyr::filter(us_states, NAME == "California")
  2. california_borders = st_cast(california, "MULTILINESTRING")
  3. raster_template2 = raster(extent(california), resolution = 0.5,
  4. crs = st_crs(california)$proj4string)

Line rasterization is demonstrated in the code below.In the resulting raster, all cells that are touched by a line get a value, as illustrated in Figure 5.22(A).

  1. california_raster1 = rasterize(california_borders, raster_template2)

Polygon rasterization, by contrast, selects only cells whose centroids are inside the selector polygon, as illustrated in Figure 5.22(B).

  1. california_raster2 = rasterize(california, raster_template2)

Examples of line and polygon rasterizations.
Figure 5.22: Examples of line and polygon rasterizations.

As with raster::extract(), raster::rasterize() works well for most cases but is not performance optimized.Fortunately, there are several alternatives, including the fasterize::fasterize() and gdalUtils::gdal_rasterize().The former is much (100 times+) faster than rasterize(), but is currently limited to polygon rasterization.The latter is part of GDAL and therefore requires a vector file (instead of an sf object) and rasterization parameters (instead of a Raster* template object) as inputs.23

5.4.4 Spatial vectorization

Spatial vectorization is the counterpart of rasterization (Section 5.4.3), but in the opposite direction.It involves converting spatially continuous raster data into spatially discrete vector data such as points, lines or polygons.

Be careful with the wording!In R, vectorization refers to the possibility of replacing for-loops and alike by doing things like 1:10 / 2 (see also Wickham (2014a)).

The simplest form of vectorization is to convert the centroids of raster cells into points.rasterToPoints() does exactly this for all non-NA raster grid cells (Figure 5.23).Setting the spatial parameter to TRUE ensures the output is a spatial object, not a matrix.

  1. elev_point = rasterToPoints(elev, spatial = TRUE) %>%
  2. st_as_sf()

Raster and point representation of the elev object.
Figure 5.23: Raster and point representation of the elev object.

Another common type of spatial vectorization is the creation of contour lines representing lines of continuous height or temperatures (isotherms) for example.We will use a real-world digital elevation model (DEM) because the artificial raster elev produces parallel lines (task: verify this and explain why this happens).Contour lines can be created with the raster function rasterToContour(), which is itself a wrapper around contourLines(), as demonstrated below (not shown):

  1. data(dem, package = "RQGIS")
  2. cl = rasterToContour(dem)
  3. plot(dem, axes = FALSE)
  4. plot(cl, add = TRUE)

Contours can also be added to existing plots with functions such as contour(), rasterVis::contourplot() or tmap::tm_iso().As illustrated in Figure 5.24, isolines can be labelled.

  1. # create hillshade
  2. hs = hillShade(slope = terrain(dem, "slope"), aspect = terrain(dem, "aspect"))
  3. plot(hs, col = gray(0:100 / 100), legend = FALSE)
  4. # overlay with DEM
  5. plot(dem, col = terrain.colors(25), alpha = 0.5, legend = FALSE, add = TRUE)
  6. # add contour lines
  7. contour(dem, col = "white", add = TRUE)

DEM hillshade of the southern flank of Mt. Mongón overlaid by contour lines.
Figure 5.24: DEM hillshade of the southern flank of Mt. Mongón overlaid by contour lines.

The final type of vectorization involves conversion of rasters to polygons.This can be done with raster::rasterToPolygons(), which converts each raster cell into a polygon consisting of five coordinates, all of which are stored in memory (explaining why rasters are often fast compared with vectors!).

This is illustrated below by converting the grain object into polygons and subsequently dissolving borders between polygons with the same attribute values (also see the dissolve argument in rasterToPolygons()).Attributes in this case are stored in a column called layer (see Section 5.2.6 and Figure 5.25).(Note: a convenient alternative for converting rasters into polygons is spex::polygonize() which by default returns an sf object.)

  1. grain_poly = rasterToPolygons(grain) %>%
  2. st_as_sf()
  3. grain_poly2 = grain_poly %>%
  4. group_by(layer) %>%
  5. summarize()

Illustration of vectorization of raster (left) into polygon (center) and polygon aggregation (right).
Figure 5.25: Illustration of vectorization of raster (left) into polygon (center) and polygon aggregation (right).