The UI and server

Each R Shiny application consists of two primary sections, which are the UI section and the server section. The UI, as the name suggests, is used to define the user interface, whereas the server section is used for executing the underlying R server side code. The shinyApp function is used in order to launch the application using the ui and server definitions.

The UI object holds the R Shiny widgets used to prepare the frontend components that the user will interact with while using the application.

A few toy examples have already been included as part of the RStudio programming environment. In order to launch an R Shiny application, run the following code in RStudio:

library(shiny)
runExample("01_hello")

This will launch a basic R Shiny app, shown as follows:

You can view the other applications available as examples by simply executing the following command:

runExample()
Valid examples are "01_hello", "02_text", "03_reactivity", "04_mpg", "05_sliders", "06_tabsets", "07_widgets", "08_html", "09_upload", "10_download", "11_timer"

The actual code of the first application (shown previously) is given as follows. Note that ui.R consists of several building blocks such as pageWithSidebar, headerPanel, sidebarPanel, and mainPanel. These are standard components that form the page layout and add structure to the overall application:

# ui.R 
library(shiny) 
 
# Define UI for application that plots random distributions  
shinyUI(pageWithSidebar( 
 
  # Application title 
  headerPanel("Hello Shiny!"), 
 
  # Sidebar with a slider input for number of observations 
  sidebarPanel( 
    sliderInput("obs",  
                "Number of observations:",  
                min = 1, 
                max = 1000,  
                value = 500) 
  ), 
 
  # Show a plot of the generated distribution 
  mainPanel( 
    plotOutput("distPlot") 
  ) 
)) 
 

R Shiny also provides a number of inputs, for example, sliderInput, textInput, selectInput, and so on. These are used for making selections such as with drop-down menus and other methods:

# server.R 
library(shiny) 
 
# Define server logic required to generate and plot a random distribution 
shinyServer(function(input, output) { 
 
  # Expression that generates a plot of the distribution. The expression 
  # is wrapped in a call to renderPlot to indicate that: 
  # 
  #  1) It is "reactive" and therefore should be automatically  
  #     re-executed when inputs change 
  #  2) Its output type is a plot  
  # 
  output$distPlot <- renderPlot({ 
 
    # generate an rnorm distribution and plot it 
    dist <- rnorm(input$obs) 
    hist(dist) 
  }) 
}) 

The preceding showcased a basic R Shiny application that allows R developers to expose the results of their work via a user friendly web interface.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.88.110