March 23, 2017

Getting Started

Access resources from CBCC website

  • Create a new folder for storing your shiny apps.
  • Place Hospitals.csv dataset in the new folder
  • Place hospitalApp.zip in new folder and unzip
  • Set your working directory to that folder
  • Install shiny, refund, and refund.shiny libraries
# set working directory to be the folder you just created
setwd("/Users/juliawrobel/Documents/How to use Shiny/")

# install libraries
install.packages("shiny")
install.packages("refund.shiny")
install.packages("refund")

Shiny is a framework in R for building interactive plots and web applications

library(shiny)
runExample("01_hello")
runExample("03_reactivity")

Run the code above to see two examples of shiny apps

Each shiny app has a ui and a server

ui

  • controls layout and appearance
  • where you add widgets
  • ui.R

server

  • instructions your computer needs to build the app
  • R code for plots, etc.
  • server.R

You can initialize a Shiny app right from RStudio

Drawing

Drawing

Choose a name for your app, set the directory, and click Create.

A Shiny app is now stored in the directory you chose

Drawing

This app generates a simple interactive histogram.

# make sure your working directory is set to where the app is saved!
library(shiny)
runApp("myfirstshiny")

Try editing the histogram app

  • Manually change color of the histogram
hist(x, breaks = bins, col = 'orange', border = 'magenta')
  • Add radio buttons to let user pick a color
# on ui.R side 
radioButtons("fillColor", label = h3("Radio buttons"),
             choices = list("Red" = "firebrick", "Yellow" = "gold", 
                            "Blue" = "cornflowerblue"), 
             selected = "firebrick")

# on server.R side
hist(x, breaks = bins, col = input$fillColor, border = 'white')
  • Make your own change! Try adding a text input widget for the title..

Place hospitals dataset in your working directory

Data on 113 hospitals collected to determine whether infection surveillance and control programs have reduced the rates of nosocomial (hospital-acquired) infection.

hospital = read.csv("/Users/juliawrobel/Documents/
Presentations and Posters/CBCC/How to use Shiny/Hospital.csv")

hospital$MEDSCHL = factor(hospital$MEDSCHL, levels = 1:2, 
                          labels = c("yes", "no"))
hospital$REGION = factor(hospital$REGION, levels = 1:4, 
                         labels = c("NE", "NC", "S", "W"))

# variable designations
cats = c("MEDSCHL", "REGION")
conts = c("LOS", "AGE", "INFRISK", "CULT", "XRAY", 
          "BEDS", "CENSUS", "NURSE", "FACS")

Open the ui.R and server.R files for the hospital app

We are going to build a shiny app for exploratory data analysis with the hospital data.

# server.R: change the following code to load Hospital.csv file
hospital = read.csv("/Users/juliawrobel/Documents
                    /Presentations and Posters/CBCC/
                    How to use Shiny/Hospital.csv")

# run the hospitals app
runApp("hospitalApp")

Add another tab to the user interface

# ui.R change from this:
    ),
    tabPanel(title = "tab 2")

# to this:
    ),
    tabPanel(title = "tab 2"), # add comma here
    tabPanel(title = "name of tab 3") # add tabPanel function here

Add a bar plot for categorical variables

# ui.R
    # add widget
    selectInput("catVar", label = h4("Select a categorical variable"), 
                choices = as.list(cats), selected = 1)
    
    # add call to build plot
       h3("Bar plot of a categorical variable"),
       plotOutput("categoricalPlot")

# server.R
  output$categoricalPlot <- renderPlot({
    # get user selected categorical variable
    catVar <- hospital[, input$catVar] 
    
    # draw the barplot
    ggplot(hospital, aes(x = catVar)) + geom_bar()
  })

skeleton for building up tab 2

replace

# ui: change this
tabPanel(title = "tab 2"),

# to this
 tabPanel(title = "tab 2",
             sidebarLayout(
               sidebarPanel(
               ),
              
               mainPanel(
                 h3("Histogram of a continuous variable grouped 
                    by categorical variable"),
                 plotOutput("mixedPlot")
               )
             ) 
             ), # end of tab 2 

Add the same bar plot to tab 2

This time we use reactive expressions! Reactive expressions give you flexibility for re-using user selected inputs and make your code faster by selectively choosing what gets updated each time.

# add to server

contInput <- reactive({
  hospital[, input$contVar]
})
catInput <- reactive({
  hospital[, input$catVar]
})

  output$mixedPlot <- renderPlot({
    # draw the barplot
    ggplot(hospital, aes(x = contInput(), fill = catInput() )) +
      geom_histogram()
  })

Your turn: add a plot to tab 3

Start with something simple. Some ideas/tips:

  • plot of residuals from a linear model
  • histogram that is grouped by a categorical variable
  • scatter plot of two selected covariates
  • refer to widgets page to learn how to code new widgets
  • when debugging make sure your R code works before you try to put it in the shiny framework!

refund.shiny: an R package for functional data analyses

notice layouts, download buttons, multiple tabs, plotly

library(refund)
library(refund.shiny)

data(cd4)

# performs functional data analysis in refund package
SC = fpca.sc(cd4)

# visualizes the results of that analysis in refund.shiny
plot_shiny(SC)

Resources