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 ---#
<- "Data/PRISM_tmax_stable_4kmD2_20180701_bil/PRISM_tmax_stable_4kmD2_20180701_bil.bil"
prism_file
#--- read in the prism data ---#
<- rast(prism_file) prism_tmax_0701_sr
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 ---
::counties(state = "Kansas", cb = TRUE) %>%
tigris#--- sp to sf ---#
st_as_sf() %>%
#--- transform using the CRS of the PRISM tmax data ---#
st_transform(terra::crs(prism_tmax_0701_sr))
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) ---#
::crop(SpatRaster, sf) terra
So, in this case, this does the job.
#--- crop the entire PRISM to its KS portion---#
<- terra::crop(prism_tmax_0701_sr, KS_county_sf) prism_tmax_0701_KS_sr
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).