RDataGuy
11/16/2019
Introduction
Well, here we go! Part 2 of our Random Number Generator RScript journey.
In this lesson we’re going to pick-up where we left off with the Random Number Generator RScript and now we’re going to take it to the next level by building a deployable Shiny Web Application. I’m really excited about this lesson!
Shiny Web Application Basics
Before we get started with developing our application, we need to cover some Shiny App basics.
The Shiny Cheat Sheet defines a Shiny Application as follows:
A Shiny app is a web page (UI) connected to a computer running a live R session (Server). Users can manipulate the UI, which will cause the server to update the UI’s displays (by running R code).
You might be asking… “What does this mean?” Well, it means that a Shiny App RScript has four basic sections.
- Section 1: Load the Shiny Library.
- Section 2: Create the HTML User Interface (UI) to collect user input.
- Section 3: Define the Server Logic (server) to utilize the collected user input to produce the desired output.
- Section 4: Run the Shiny App using the defined UI & server code.
Heres what these four basic sections look like in an RScript.
library(shiny)
ui <- fluidPage()
server <- function(input, output){}
shinyApp(ui = ui, server = server)
Now that you have a little better idea of what the RScript is doing, your next thought might be “How do I get this application on the web? I don’t have an R Server and I’m not planning on leaving my laptop connected to the internet 24/7/365 to be a server!”
Well don’t worry because RStudio offers a place for you to deploy and share your web applications! The name of this place is shinyapp.io and it’s a fantastic website for anyone interested in developing their own Shiny web applications. The site has access packages available for every level of need from the R Hobbiest to the Large Corporation.
Our Goal
Our end goal is to produce a Shiny Web Application using the code we wrote in Lesson 8. When we’re all done it should look a little something like this.
Step #1: Create the Application Script
Okay, so let’s dive in and create our Application Script file. This will be were we build the “guts” of the application using our code from Lesson 8.
To create the Shiny Web Application Script file also known as “app.R”, click on the “New File” button and select “Shiny Web App…”
This will bring up a window where you can name the application. You should know that you can’t have any spaces in the application name. So, instead of spaces, I use "_" or “-”. In this case, let’s name the application “random_numbers”. Then click the “Create” button.
When the “app.R” script file is generated, there will be example code in the file but we’re not going to use this code. We’re going to modify it to meet our needs. Here’s the code you get when you generate the “app.R” file.
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
}
# Run the application
shinyApp(ui = ui, server = server)
Step #2: Clean-up The Example Code
We need to clean-up the sample code by replacing the header information with our personal header information as well as by removing the code we’re not going to use (e.g. the slider bar, the histogram plot, etc.). Once your file is cleaned-up it should look like this:
# HEADER --------------------------------------------
#
# Author: Your Name
# Copyright (c) Your Name, 2019
# Email: your_email@your_domain.com
#
# Date: Today's Date
#
# Shiny App Name: Random Number Generator
#
# Shiny App Description: Generate a defined number of random values
# for a given range of numbers.
#
#
# Notes:
# This is a single file Shiny App.
#
# LOAD LIBRARIES ------------------------------------
library(shiny)
# USER INTERFACE ------------------------------------
# Define UI for application that generates a list of random numbers
ui <- fluidPage(
# Application title
titlePanel("Random Number Generator"),
# Sidebar with inputs for the randome number generator
sidebarLayout(
sidebarPanel(
# OUR NEW CODE WILL GO HERE
),
# Show a table of random numbers
mainPanel(
# OUR NEW CODE WILL GO HERE
)
)
)
# SERVER INFORMATION --------------------------------
# Define server logic required to display table of random numbers
server <- function(input, output) {
# OUR NEW CODE WILL GO HERE
}
# RUN APPLICATION ----------------------------------
shinyApp(ui = ui, server = server)
Step #3: Add our code
Our Shiny Web App is divided into two areas:
- A User Interface (UI) that contains:
- A “Side Panel” with 4 user inputs and an action button for the user to press to start the random number generator.
- Numeric Input called “values” for number of values the user needs.
- Numeric Input called “rangeStart” for start of range of numbers to use.
- Numeric Input called “rangeEnd” for end of range of numbers to use.
- Two Radio Buttons called “dupes” for users to decide if they want to sample with replacement.
- Action Button called “do” for user to press to initiate the random number generator calculations on the server:
- A “Main Panel” where the rendered tabluar output called “randomNumbers” will be displayed.
- A “Side Panel” with 4 user inputs and an action button for the user to press to start the random number generator.
- Server logic that contains:
Reactive Event on the server that executes our code using the user’s 4 input values (e.g. values, rangeStart, rangeEnd, dupes) to generate random numbers once the user clicks on the “do” Action Button called “Generate!” and stores the generated numbers in a variable called “random_data”.
Render the reactive event data, “random_data”, into a tablular output format called “randomNumbers” which is displayed in the UI’s Main Panel.
Here’s what the finished code looks like.
# HEADER --------------------------------------------
#
# Author: RDataGuy
# Copyright (c) RDataGuy, 2019
# Email: rdataguy@gmail.com
#
# Date: 2019-11-16
#
# Shiny App Name: Random Number Generator
#
# Shiny App Description: Generate a defined number of random values
# for a given range of numbers.
#
#
# Notes:
# This is a single file Shiny App.
#
# LOAD LIBRARIES ------------------------------------
library(shiny)
# USER INTERFACE ------------------------------------
# Define UI for application that generates a list of random numbers
ui <- fluidPage(
# Application title
titlePanel("Random Number Generator"),
# Sidebar with inputs for the randome number generator
sidebarLayout(
sidebarPanel(
numericInput("values",
"Number of Values:",
5),
numericInput("rangeStart",
"Range Start",
1),
numericInput("rangeEnd",
"Range End",
5),
radioButtons("dupes",
"Duplicates?",
choices = c(TRUE,FALSE),
selected = FALSE),
br(), # adds a blank line
actionButton("do", "Generate!")
),
# Show a table of random numbers using the Server's output called "randNumbers"
mainPanel(
tableOutput("randNumbers")
)
)
)
# SERVER INFORMATION --------------------------------
# Define server logic required to display table of random numbers
server <- function(input, output) {
# Use an action button as an event to generate the list of random numbers
random_data <- eventReactive(input$do, {
# Randomly sample values from the specified range
numbers <- seq(input$rangeStart:input$rangeEnd)
sample(numbers, input$values, replace = as.logical(input$dupes))
})
# Output the list of random numbers only AFTER the "Generate!" button is pressed
output$randNumbers <- renderTable({
random_data()
}, rownames = FALSE, colnames = FALSE)
}
# RUN APPLICATION ----------------------------------
shinyApp(ui = ui, server = server)
Step #4: Test our Web Application
Okay! Let’s test it! To test your application, click on the “Run App” button.
You should see a web page pop up. Try clicking on the “Generate!” button. You should see output similar to this.
Step #5: Deploy our Web Application
Alright! Time to deploy this baby!
- First, you need to install the “rsconnect” package & load the library:
- Next, you need to create a shinyapps.io account. If you have a Google or GitHub account, you can just sign in with that and setup your profile.
- Create a token on shinyapps.io so you can configure “rsconnect” so you can deploy your app to shinyapps.io from RStudio using the “rsconnect” package. Click on your profile pic in the upper right corner and click on the “tokens” option.
After you create your token you should see a window with your rsconnect configuration information.
Click the copy to clipboard button and paste in your RStudio Console.
Rsconnect is now configured to deploy your application to shinyapps.io!
Next, go to your “app.R” script and click on the “Publish” button or in your RStudio Console type “deployApp()”.
After you deploy your application the browser window should pop up with your newly deployed web application. Here’s mine for you check out.
Conclusion
I hope you enjoyed these last two lessons and found them helpful.
Enjoy!
Have fun coding!