Module 2.1

Line Chart App Setup

Prework
  • Get a FRED API key
  • Install fredr, read about its basic usage and have a look at the FRED website
  • Install ecm, which we will use to build our recession shading helper script
  • Install shinyWidgets and familiarize yourself with its basic functions
  • Start a new Shiny project for this lesson. Go to File, select New Directory and then Shiny App. Browse to where you want to save the app, give the directory a name and click Create Project.
  • Read this article about sliders

Overview

A fundmental concept in R Shiny is reactivity. Reactivity refers to the automatic responsiveness and dynamic behavior of the application based on user input and data changes. It allows the application to update and re-render specific parts of the user interface (UI) in response to changes in input values, data updates, or other reactive triggers.

All Shiny apps have an element of reactivity. In a basic Shiny app like we say in the last module, reactivity occurs when user input is fed to the server function through functions like renderPlot() or renderTable(). But we might also want to add additional elements of reactivity by using reactive functions like reactive() or observe().

The app that we are going to build over the next few modules is going to look at how to use the reactive() function to control two separate reactive inputs to a line chart: the indicator the user wishes to view and the date range that the way to view it for. Here is the app that we are going to be building:

Setup

In the setup portion of our we want to start by loading the packages we will need to build the app. For this app, we are going to be using the fredr package to download data pertaining to the overall health of the economy from the St. Louis Fed’s Federal Reserve Economic Data (FRED)[https://fred.stlouisfed.org/] API. So here we will also set our FRED API key and assign the codes for the indicators that we want to download to objects.

Next, we will use the as.Date() function to set the start date of our line series to Januar 1, 1970 and the end date as today’s date (system date). We will also create a list of variable names for our UI dropdown (vars) and relate them to the objects containing the indicator codes.

Finally, we are going to be using a helper function to generate recession shading for our charts. Scroll down to the bottom of this page to see the code for the helper function. Take this and save it in an R file and put it in your app folder. In this chunk, we are going to call it with the source function, e.g. source(helper.R).

# Load packages
library(shiny)
library(fredr)
library(dplyr)
library(ggplot2)

# Set Fred API key 
fredr_set_key("YOUR FRED API KEY") 

# Assign FRED series to objects
cci <- "CSCICP03USM665S" # consumer confidence
bci <- "BSCICP03USM665S" # business confidence
cli <- "USALOLITONOSTSAM" # composite lead indicator
unemp_rate <- "UNRATE" # unemployment rate
growth <- "A191RL1Q225SBEA" # growth rate

# set start and end date
start_date <- as.Date("1970-01-01")
end_date <- as.Date(Sys.Date())

# Create list of named values for the input selection
vars <- c("Consumer Confidence" = cci, 
          "Business Confidence" = bci, 
          "Composite Indicator" = cli, 
          "Unemployment Rate" = unemp_rate,
          "Growth Rate" = growth)

# Load helper script
source("helper.R") # scroll down, code pasted below

Helper script

This is the helper script for shaded recession rectangles. Save in a file called helper.R in same folder as your app.R file. See this post for more details.

library(ecm) # forlagpad

# define add_rec_shade function
add_rec_shade<-function(st_date,ed_date,shade_color, y_min, y_max) {
  
  # download NBER recession indicators, peak through trough
  recession<- fredr(series_id = "USRECD",
                    observation_start = as.Date(st_date), 
                    observation_end = as.Date(ed_date))
  
  #code 1 for 1st day of recession, -1 for 1st day after it ends
  recession$diff<-recession$value-lagpad(recession$value,k=1)
  
  #drop 1st N.A. value
  recession<-recession[!is.na(recession$diff),] 
  
  #create vector of recession start dates
  recession.start<-recession[recession$diff==1,]$date 
  
  #create vector of recession end dates
  recession.end<-recession[recession$diff==(-1),]$date 
  
  # if there are more dates listed in recession.start than recession.end
  if(length(recession.start)>length(recession.end))
  # then enter system date for last date in recession.end
  {recession.end<-c(recession.end,Sys.Date())} 
  
  # if there are more dates listed in recession.end than recession.start
  if(length(recession.end)>length(recession.start))       
  # then enter the earliest date in recession$date as first date in recession.start  
  {recession.start<-c(min(recession$date),recession.start)} 
  
  # make a dataframe out of recession.start and recession.end
  recs<-as.data.frame(cbind(recession.start,recession.end))
  
  # convert recession.start into a date
  recs$recession.start<-as.Date(
    as.numeric(recs$recession.start),
    origin=as.Date("1970-01-01")) 

  # convert recession.end into a date
  recs$recession.end<-as.Date(
    recs$recession.end,
    origin=as.Date("1970-01-01")) 
  
  # if the number of rows in recs > 0
  if(nrow(recs)>0) 
  # draw the rectangle  
  {rec_shade<-geom_rect(data=recs, 
                         # inherit.aes=F overrides default aesthetics
                         inherit.aes=F, 
                         aes(xmin=recession.start, 
                         xmax=recession.end, 
                         ymin=y_min, ymax=y_max), 
                         fill=shade_color, alpha=0.5)
    return(rec_shade)
  }
}