R Notebooks are a ‘flavor’ of R markdown that combine plain text and R commands in code chunks. You can download the Rmd file from the ‘code’ button at the top of the page, then open it in RStudio. You run code chunks in the document line-by-line, and the output appears immediately below the code chunk. When you save the Rmd file, it automatically creates a HTML file showing results from all the code that has been run so far.
If you’re in RStudio, you can minimize the console window (and probably close the right-hand panes as well). You won’t need it, because when you run R commands in a R Notebook the output appears below the code chunk (not the console). This takes some getting used to.
Keyboard shortcuts:
- run the current line of R: ctrl + enter
- run everything in the current code chunk: ctrl + shift + enter
- insert a new code chunk: ctrl + alt + i
Install caladaptr
:
if (!require(devtools)) {install.packages("devtools"); library(devtools)}
Loading required package: devtools
Loading required package: usethis
The working directory was changed to D:/GitHub/cal-adapt/caladaptr inside a notebook chunk. The working directory will be reset when the chunk is finished running. Use the knitr root.dir option in the setup chunk to change the working directory for notebook chunks.
#
# devtools::install_github("ucanr-igis/caladaptr")
library(caladaptr)
Registered S3 methods overwritten by 'dbplyr':
method from
print.tbl_lazy
print.tbl_sql
Registered S3 methods overwritten by 'htmltools':
method from
print.html tools:rstudio
print.shiny.tag tools:rstudio
print.shiny.tag.list tools:rstudio
Registered S3 method overwritten by 'htmlwidgets':
method from
print.htmlwidget tools:rstudio
caladaptr (version 0.4.5)
URL: https://ucanr-igis.github.io/caladaptr
Bug reports: https://github.com/ucanr-igis/caladaptr/issues
## Make sure you have version 0.4.1 caladaptr or later.
packageVersion("caladaptr")
[1] ‘0.4.5’
Now we can load the other packages we’ll be using below:
pkgs_req <- c("ggplot2", "dplyr", "tidyr", "lubridate", "conflicted")
pkgs_missing <- pkgs_req[!(pkgs_req %in% installed.packages()[,"Package"])]
if (length(pkgs_missing)) install.packages(pkgs_missing, dependencies=TRUE)
library(units)
library(ggplot2)
library(dplyr)
library(conflicted)
library(tidyr)
library(tmap)
library(lubridate)
library(sf)
The last setup task is to define your preferences when you use an ambiguous function name (i.e., a function that exists in more than one package). This is particularly needed with a few common generic functions from dplyr
:
conflict_prefer("filter", "dplyr", quiet = TRUE)
conflict_prefer("count", "dplyr", quiet = TRUE)
conflict_prefer("select", "dplyr", quiet = TRUE)
Goal: Make a time series plot of projected maximum annual temperature for a single point, using the four recommended GCMs for California under RCP 4.5.
The first step in getting climate variables back is to create a Cal-Adapt API request object. This involves stringing together a series of functions that specify the pieces of the request. The following constants can help you specify pieces of the request:
cap1 <- ca_loc_pt(coords = c(-121.4687, 38.5938)) %>%
ca_gcm(gcms[1:4]) %>%
ca_scenario(c("rcp45", "rcp85")) %>%
ca_period("year") %>%
ca_years(start = 2030, end = 2080) %>%
ca_cvar(c("tasmax"))
Entering the name of an API request object at the console will display its components:
cap1
Cal-Adapt API Request
Location(s):
x: -121.469
y: 38.594
Variable(s): tasmax
Temporal aggregration period(s): year
GCM(s): HadGEM2-ES, CNRM-CM5, CanESM2, MIROC5
Scenario(s): rcp45, rcp85
Dates: 2030-01-01 to 2080-12-31
Tip: You don’t have to memorize a bunch of keywords. caladaptr provides several constants that contain the values you can pass to API construction functions, including gcms
, scenarios
, cvars
, and periods
.
## Available global change models
## Note, the first 4 GCMs are the recommended priority models for California
gcms
[1] "HadGEM2-ES" "CNRM-CM5" "CanESM2" "MIROC5" "ACCESS1-0" "CCSM4" "CESM1-BGC" "CMCC-CMS"
[9] "GFDL-CM3" "HadGEM2-CC" "ens32avg" "ens32max" "ens32min"
## Available emissions scenarios
scenarios
[1] "rcp45" "rcp85" "historical"
## Available climate variables
cvars
[1] "tasmax" "tasmin" "pr" "swe"
## Available temporal aggregation periods
periods
[1] "day" "month" "year" "30yavg"
Note: Cal-Adapt has data for many but by no means all combinations of the above constants.
You can use these values as arguments to build up the API request:
To verify the location in an API request, you can plot it. (Note we still haven’t fetched any climate data yet, this just shows you the location the request will ask for.)
plot(cap1)
Now it’s time to fetch data with ca_getvals_tbl()
. The object returned by ca_getvals_tbl()
is tibble (data frame):
cap1_tbl <- cap1 %>%
ca_getvals_tbl(quiet = TRUE)
cap1_tbl
To produce the desired time series plot, we need to i) pull out just values for RCP 4.5, and ii) convert degrees to °F. For the unit conversion, we can use the handy set_units
function from the units
package.
cap1_rcp45_tbl <- cap1_tbl %>%
filter(scenario == "rcp45") %>%
mutate(temp_f = set_units(val, degF))
cap1_rcp45_tbl
Plot these with ggplot:
ggplot(data = cap1_rcp45_tbl, aes(x = as.Date(dt), y = as.numeric(temp_f), group = gcm)) +
geom_line(aes(color=gcm)) +
labs(title = "Average Annual Maximum Temperature for RCP4.5", x = "year", y = "temp (F)")
Modify the above to create a similar plot for RCP 8.5.
## Plot of RCP 8.5 goes here
Goal: produce a time series plot showing the difference between RCP85 and RCP45 on maximum annual temperature for a single county.
The Cal-Adapt API has a number of ‘preset’ areas-of-interest (also called boundary layers) that you can use cookie-cutter style when retrieving climate data. The advantage of using an AOI Preset is that you don’t need to import a GIS layer to query according to these common features. You just need to know the name or ID number of the feature(s) you’re interested in.
The following AOI Presets are available:
aoipreset_types
[1] "censustracts" "counties" "cdistricts" "ccc4aregions" "climregions"
[6] "hydrounits" "irwm" "electricutilities" "wecc-load-area" "evtlocations"
[11] "place"
To use an AOI Preset, you need to specify which feature(s) you’re interested in by providing the value(s) for one of the id fields. The specific columns available for identifying features vary according to preset. You can view the id columns and their values for an AOI Preset using the built-in aoipreset_idval
constant. For example the counties layer allows you to specify a county by name, fips code, or id. Remember that everything in R is case-sensitive!
aoipreset_idval$counties
You can find county fips codes on Google - just be sure to use the 6-character version which includes the state. Alternately, you can plot the county preset layer and click on your county of interest:
counties_sf <- ca_aoipreset_geom("counties")
Reading layer `counties' from data source `C:\Users\Andy\AppData\Local\R\cache\R\caladaptr\counties.gpkg' using driver `GPKG'
Simple feature collection with 87 features and 54 fields
geometry type: MULTIPOLYGON
dimension: XY
bbox: xmin: -13871160 ymin: 3833648 xmax: -12625080 ymax: 5416187
projected CRS: WGS 84 / Pseudo-Mercator
tmap_mode("view")
tm_shape(counties_sf) + tm_polygons()