5.1 Cropping to the Area of Interest

Here we use PRISM maximum temperature (tmax) data as a raster dataset and Kansas county boundaries as a vector dataset.

Let’s download the tmax data for July 1, 2018 (Figure 5.1).

#--- set the path to the folder to which you save the downloaded PRISM data ---#
# This code sets the current working directory as the designated folder
options(prism.path = "Data")

#--- download PRISM precipitation data ---#
get_prism_dailys(
  type = "tmax",
  date = "2018-07-01",
  keepZip = FALSE
)

#--- the file name of the PRISM data just downloaded ---#
prism_file <- "Data/PRISM_tmax_stable_4kmD2_20180701_bil/PRISM_tmax_stable_4kmD2_20180701_bil.bil"

#--- read in the prism data ---#
prism_tmax_0701_sr <- rast(prism_file)
Map of PRISM tmax data on July 1, 2018

Figure 5.1: Map of PRISM tmax data on July 1, 2018

We now get Kansas county border data from the tigris package (Figure 5.2) as sf.

#--- Kansas boundary (sf) ---#
KS_county_sf <-
  #--- get Kansas county boundary ---
  tigris::counties(state = "Kansas", cb = TRUE) %>%
  #--- sp to sf ---#
  st_as_sf() %>%
  #--- transform using the CRS of the PRISM tmax data  ---#
  st_transform(terra::crs(prism_tmax_0701_sr))
Kansas county boundaries

Figure 5.2: Kansas county boundaries


Sometimes, it is convenient to crop a raster layer to the specific area of interest so that you do not have to carry around unnecessary parts of the raster layer. Moreover, it takes less time to extract values from a raster layer when the size of the raster layer is smaller. You can crop a raster layer by using terra::crop(). It works like this:

#--- syntax (this does not run) ---#
terra::crop(SpatRaster, sf)

So, in this case, this does the job.

#--- crop the entire PRISM to its KS portion---#
prism_tmax_0701_KS_sr <- terra::crop(prism_tmax_0701_sr, KS_county_sf)

The figure below (Figure 5.3) shows the PRISM tmax raster data cropped to the geographic extent of Kansas. Notice that the cropped raster layer extends beyond the outer boundary of Kansas state boundary (it is a bit hard to see, but look at the upper right corner).

PRISM tmax raster data cropped to the geographic extent of Kansas

Figure 5.3: PRISM tmax raster data cropped to the geographic extent of Kansas