Loading [MathJax]/jax/output/CommonHTML/jax.js
+ - 0:00:00
Notes for current slide
Notes for next slide

Building Shiny Apps

MACS 20400
University of Chicago

1 / 43

What is Shiny?

  • R package from RStudio
  • Web application framework for R
  • R code interactive web page
  • No HTML/CSS/Javascript knowledge required
  • Great for sharing R analysis with someone scared of R
2 / 43

Dating age rule

3 / 43

What is a Shiny app?

  • Computer running R
  • Web page
  • Computer performs calculations, sends contents to web page
  • User interacts with web page, sends updates back to computer
  • Rinse and repeat
4 / 43

City of Chicago wage employees

5 / 43

Shiny app template

library(shiny)
ui <- fluidPage()
server <- function(input, output) {}
shinyApp(ui = ui, server = server)

Important: Do not place any code after shinyApp()

6 / 43

Run Shiny app in RStudio, method 1

Save file as app.R "Run" button turns to "Run App"

Good for creating Shiny apps quickly, all code in one file

7 / 43

Run Shiny app in RStudio, method 2

Save UI as ui.R and server as server.R in same directory

Good for complex Shiny apps, separates view vs logic

If using this method, do not include a call to shinyApp(...)

8 / 43

Run Shiny app in RStudio, method 3

File > New File > Shiny Web App...

Generates the template for you

9 / 43

Stop Shiny app in RStudio

Press "Esc" or click the Stop icon

10 / 43

Exercise: create the basic app

  • usethis::use_course("cis-ds/shiny-demo")
  • Create a basic Shiny app
  • Import the City of Chicago wage employee data file
11 / 43

Add elements to app inside fluidPage()

library(shiny)
ui <- fluidPage("Hello CFSS")
server <- function(input, output) {}
shinyApp(ui = ui, server = server)

12 / 43

Add elements to app inside fluidPage()

fluidPage(
h1("My Shiny app"),
"Hello CFSS"
)

13 / 43

Add HTML to fluidPage()

  • Remember the UI simply creates HTML
  • Can use any HTML tags
    • h1() = header1
    • br() = line break
    • strong() = bold text
  • Any HTML tag can be accessed using tags object
    • h1 = tags$h1(), br = tags$br()
  • Common tags can be accesed without tags
14 / 43

Add HTML to fluidPage()

fluidPage(
h1("My Shiny app"),
h3("Subtitle"),
"Hello",
"CFSS",
br(),
strong("bold text")
)

15 / 43

Use a layout

16 / 43

sidebarLayout()

fluidPage(
titlePanel("My Shiny app"),
sidebarLayout(
sidebarPanel(
"This is a side panel"
),
mainPanel(
"And this is the main stuff"
)
)
)
17 / 43

sidebarLayout()

18 / 43

Exercise: add a layout

  • Define the layout for the application
  • Add an app title
  • Identify where inputs and outputs will go
19 / 43

Inputs and outputs

  • For interactivity, app needs inputs and outputs
  • Inputs - things user can toggle/adjust
  • Output - R objects user can see, often depend on inputs
20 / 43

Inputs

library(shiny)
ui <- fluidPage(
sliderInput(
"num", "Choose a number",
min = 0, max = 100,
value = 20)
)
server <- function(input, output) {}
shinyApp(ui = ui, server = server)

21 / 43

Inputs

sliderInput("num", "Choose a number",
min = 0, max = 100, value = 20)
## <div class="form-group shiny-input-container">
## <label class="control-label" id="num-label" for="num">Choose a number</label>
## <input class="js-range-slider" id="num" data-skin="shiny" data-min="0" data-max="100" data-from="20" data-step="1" data-grid="true" data-grid-num="10" data-grid-snap="false" data-prettify-separator="," data-prettify-enabled="true" data-keyboard="true" data-data-type="number"/>
## </div>
22 / 43

Inputs

23 / 43

Inputs

sliderInput("num",
"Choose a number",
min = 0,
max = 100,
value = 20)
  • Input name
  • Label to display
  • Input-specific arguments
24 / 43

Exercise: add inputs

  • Add inputs for
    • Wage
    • Full/part-time
    • Department
25 / 43

Outputs

Function Outputs
plotOutput() plot
tableOutput() table
uiOutput() Shiny UI element
textOutput() text
  • Plots, tables, text - anything that R creates and users see
  • Initialize as empty placeholder space until object is created
26 / 43

Outputs

library(shiny)
ui <- fluidPage(
sliderInput("num", "Choose a number",
0, 100, 20),
plotOutput("myplot")
)
server <- function(input, output) {}
shinyApp(ui = ui, server = server)

27 / 43

Exercise: add placeholders for output

  • Add placeholders for a
    • Histogram
    • Table
28 / 43

Server: assemble input into outputs

server <- function(input, output) {
output$myplot <- renderPlot({
plot(rnorm(input$num))
})
}
  1. Save objects into output$
  2. Build objects with render*()
29 / 43

Output() render*()

Output function Render function
plotOutput() renderPlot({})
tableOutput() renderTable({})
uiOutput() renderUI({})
textOutput() renderText({})
30 / 43

render*() functions

renderPlot({
plot(rnorm(100))
})
31 / 43

Server: assemble input into outputs

server <- function(input, output) {
output$myplot <- renderPlot({
plot(rnorm(input$num))
# in UI:sliderInput("num", ...)
})
}
  1. Save objects into output$
  2. Build objects with render*()
  3. Access input values with input$
32 / 43

Exercise: add output

  • Create a histogram of hourly wages for selected employees
  • Add a table showing the count of selected employees per department
33 / 43

Reactivity

  • Shiny uses reactive programming
  • Reactive variables
    • When value of variable x changes, anything that relies on x is re-evaluated
    • Contrast with regular R:
      x <- 5
      y <- x + 1
      x <- 10
34 / 43

Reactivity

  • input$num is a reactive value
    output$myplot <- renderPlot({
    plot(rnorm(input$num))
    })
  • output$myplot depends on input$num
    • input$num changes output$myplot reacts
  • All inputs are automatically reactive, so if you use any input inside a render* function, the output will re-render any time input changes
35 / 43

Reactive contexts

  • You can define your own reactive variables
  • Reactive values can only be used inside reactive contexts
  • Any render* function is a reactive context
  • Use reactive({...}) to assign a reactive variable
  • Use observe({...}) to access a reactive variable
  • Remember: reactive variable means anything that depends on it gets re-executed automatically
36 / 43

Reactive contexts

Assign variable

server <- function(input, output) {
x <- input$num + 1
}
# error
server <- function(input, output) {
x <- reactive({
input$num + 1
})
}
# OK

Access variable

server <- function(input, output) {
print(input$num)
}
# error
server <- function(input, output) {
observe({
print(input$num)
})
}
# OK
37 / 43

Simple Shiny app using basic reactivity

library(shiny)
ui <- fluidPage(
sliderInput("num", "Choose a number",
0, 100, 20),
plotOutput("myplot")
)
server <- function(input, output) {
output$myplot <- renderPlot({
plot(seq(input$num))
})
x <- reactive({
input$num + 1
})
observe({
print(x())
})
}
shinyApp(ui = ui, server = server)
38 / 43

Exercise: make your code more efficient

  • Create a reactive data frame employ_filter that creates the filtered data frame
  • Use employ_filter to create the histogram and table
39 / 43

Create UI elements dynamically

  • uiOutput()
  • Changing input values based on other inputs
40 / 43

Basic example of uiOutput()

library(shiny)
ui <- fluidPage(
numericInput("num", "Maximum slider value", 5),
uiOutput("slider")
)
server <- function(input, output) {
output$slider <- renderUI({
sliderInput("slider", "Slider", min = 0,
max = input$num, value = 0)
})
}
shinyApp(ui = ui, server = server)
41 / 43

Exercise: Populate the job titles

  • Use uiOutput() in our app to populate the job titles input
42 / 43

Share your app: shinyapps.io

  • Go to http://www.shinyapps.io/ and make an account
  • Make sure all your app files are in an isolated folder
  • Click "Publish Application" in RStudio
    • You might be asked to install a couple packages
    • Follow instructions from RStudio
43 / 43

What is Shiny?

  • R package from RStudio
  • Web application framework for R
  • R code interactive web page
  • No HTML/CSS/Javascript knowledge required
  • Great for sharing R analysis with someone scared of R
2 / 43
Paused

Help

Keyboard shortcuts

, , Pg Up, k Go to previous slide
, , Pg Dn, Space, j Go to next slide
Home Go to first slide
End Go to last slide
Number + Return Go to specific slide
b / m / f Toggle blackout / mirrored / fullscreen mode
c Clone slideshow
p Toggle presenter mode
t Restart the presentation timer
?, h Toggle this help
Esc Back to slideshow