Getting Started with Shiny
Intro to Shiny

Colin Rundel

Shiny

Shiny is an R package that makes it easy to build interactive web apps straight from R. You can host standalone apps on a webpage or embed them in R Markdown documents or build dashboards. You can also extend your Shiny apps with CSS themes, htmlwidgets, and JavaScript actions.

Shiny App


Server

+


Client / Browser

+ +

Anatomy of an App

library(shiny)

shinyApp(
  ui = list(),
  
  server = function(input, output, session) {
  
  }
)

Demo 01 - A Basic Example

demos/demo01.R

library(tidyverse)
library(shiny)
d = readr::read_csv(here::here("data/weather.csv"))

shinyApp(
  ui = fluidPage(
    titlePanel("Temperature Forecasts"),
    sidebarLayout(
      sidebarPanel(
        radioButtons(
          "city", "Select a city",
          choices = c("Chicago", "Durham", "Sedona", "New York", "Los Angeles")
        ) 
      ),
      mainPanel( 
        plotOutput("plot")
      )
    )
  ),
  server = function(input, output, session) {
    output$plot = renderPlot({
      d |>
        filter(city %in% input$city) |>
        ggplot(aes(x=time, y=temp, color=city)) +
        geom_line()
    })
  }
)

Your turn - Exercise 01

Copy the code from the previous slide (or open exercises/ex01.R) and try running it using the Run App button.

Check that you are able successfully run the shiny app and are able to interact with it.

  • If everything is working try modifying the code (e.g. try adding or removing a city from radioButtons()).

  • What happens if you add a city that is not in the weather.csv data set to the radio button input?

05:00

Troubleshooting

A couple of quick tips:

  • If the app can’t find the data, make sure you have opened the workshop’s RStudio project

  • Make sure you have the latest versions of shiny and tidyverse installed

  • If you are stuck, ask a neighbor for help and/or raise your hand and myself or a TA will come by

Layouts

Multi-row layout

Other layouts

Input Widgets

A brief widget tour

rundel.shinyapps.io/widgets/

Your turn - Exercise 02

We’ve just seen a number of alternative input widgets.

Starting from the code in exercises/ex02.R try changing the radioButton() input to something else.

What happens if you use an input capable of selecting multiple values

  • e.g. checkboxGroupInput()

  • or selectInput(multiple = TRUE)?

06:00