A Tale of Two Files

Shiny applets are defined by two files, ui.R and server.R. These two files are enough to create a simple shiny applet.

  • ui.R defines the page layout and user interface
  • server.R contains the R code to create any output

ui.R

library(shiny)

# A simple/common user interface template
shinyUI(fluidPage(

  # Application title
  titlePanel("Title"),
  
  sidebarPanel(
    # Define some inputs here
  ),
  
  mainPanel(
    # output (from the server) go here
  )

))

ui.R

  • Defines the shinyUI() function, which contains elements that describe the HTML page

  • Typical applets are constructed using the pageWithSidebar() function, which creates a side bar generally used for input and a main panel used for output

  • Elements are hierarchical functions: components in the sidebar go into the sidebarPanel() function, separated by commas

  • Input variables are named in ui.R and then referenced in server.R

User Interface Example

User interface code for creating Example_01.r:

ui <- fluidPage(
  # Application title
  titlePanel("Summary Statistics"),
  # Sidebar panel
  sidebarLayout(
    sidebarPanel(
      # Option to upload file
      fileInput('data', 'Please upload your data file',
                accept=c('text/csv', 
                         'text/comma-separated-values,text/plain', 
                         '.csv')),
      # Numeric option to change n parameter in head() function
      numericInput('headcount', 'How many rows would you like to display', 
                   6, min = 1, max = 100)

    ),
    # Main panel
    mainPanel(
      verbatimTextOutput("sum") # Displays the summary text
    )
  ),
  tableOutput('contents') # Displays table
)

server.R

library(shiny)

# Server side logic 
shinyServer(function(input, output) {
  # do something
})

server.R

  • Defines the shinyServer(), which is a function with input and output variables.
  • Contains all of the R code to generate any output
  • (Later) can also be used to modify inputs
  • Generally much longer than ui.R - all the interesting stuff happens in server.R

Server Example

Server code for creating Example_01.r:

server <- function(input, output) {
  
  # Define dataframe to be accessible for later use
  dataframe <- reactive({
    dataset <- input$data
    if (is.null(dataset))
      return(NULL)
    read.csv(dataset$datapath, header=T)
  })
  # Renders summary output
  output$sum <- renderPrint({
    summary(dataframe())
  })
  # Renders table preview with input parameter
  output$contents <- renderTable({
    head(dataframe(),input$headcount)
  })
}

Your Turn

Using Example_01.R:

  1. Change the default numeric input to 10 in numericInput
  2. Upload various sports data sets and toggle the number of rows to get an understanding of the functionality.

Answers

1.

# In user interface
numericInput('headcount', 'How many rows would you like to display', 
                   10, min = 1, max = 100)

Shiny Interactivity for Example_01.R

Input

  • File Upload
  • Numeric Input

Output

  • Text
  • Table

There are many additional ways for users to interact with shiny!

Reactivity

Shiny applets work because of reactive expressions, which automatically update outputs when input values change.

input values => R code => output values

Reactive expressions keep track of what values they read and what values they change. If those values become "out of date", they know their return value is out of date and will automatically recalculate.

Reactivity

We can create a reactive expression by passing a normal expression into reactive.

dataInput <- reactive({
        c("Nike","Reebok","Under Armor") 
})

This statement stores the corresponding data into the variable dataInput which we can then call later in our server code.

Reactivity

Reactive values can be turned into output objects that are passed to the shinyServer function.

This output depends on both the dataset and the number of observations.

output$view <- renderTable({
   head(dataInput(), n = input$obs)
})

Whenever either the dataset or the number of observations changes, this function will be re-executed and the output will change.

Your Turn

Explore the code for the Example_01.r applet.

  1. What is the name of the R variable that contains the dataset name?
  2. Instead of displaying the summary, create a histogram of the seasonal at bats using the MLB Stats.csv dataset. Remember to load ggplot2
  3. Name your shiny app accordingly.

Answers

1.

dataframe

# In server
  dataframe <- reactive({
    dataset <- input$data
    if (is.null(dataset))
      return(NULL)
    read.csv(dataset$datapath, header=T)
  })

2.

# In user interface
  plotOutput("histplot")

# In server
  output$histplot <- renderPlot({
    qplot(dataframe()[,8], main = "Histogram of At Bats for MLB Data Set")+
      labs(x = "Number of At Bats Per Season", y = "Frequency")
  })