You are on page 1of 14

5/24/22, 4:19 PM Build Your First Shiny Web App in R | by Chanin Nantasenamat | Towards Data Science

Open in app Get started

Published in Towards Data Science

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Chanin Nantasenamat Follow

Aug 4, 2020 · 9 min read · Listen

Save

Image drawn by Author

DATA SCIENCE

Build Your First Shiny Web App in R


Shiny Tutorial Episode 1

Do you want to make your R code publicly available for others to use? If you
answered yes, then this article is for you as I will be showing you how to build
your very first web application in R using the Shiny package.

To supplement this article, you can also watch this tutorial video Building Your First Web
Application in R that I made on my YouTube channel called the Data Professor.

https://towardsdatascience.com/build-your-first-shiny-web-app-in-r-72f9538f9868 1/14
5/24/22, 4:19 PM Build Your First Shiny Web App in R | by Chanin Nantasenamat | Towards Data Science

Open in app Get started


Web Apps in R: Building your First Web Application in R | Shiny Tutorial E…
E…

Data Science Life Cycle


The data science life cycle starts with the collection
163 of
2 data that will serve as the dataset

and the core component of a data science project. Next, this dataset needs to be cleaned to
void itself of missing data as well as any abnormalities. As the name implies, exploratory
data analysis (EDA) will allow us to take a glimpse of the general characteristics of the
dataset and this can be attained by performing descriptive statistics and data
visualizations. Insights gained from EDA may provide starting points and ideas for
building predictive models (e.g. classification, regression, clustering, association analysis,
etc.). To complete the life cycle the best performing model can be deployed as an
application programming interface (API) and web application.

Data Science Life Cycle. (Drawn by Chanin Nantasenamat)

https://towardsdatascience.com/build-your-first-shiny-web-app-in-r-72f9538f9868 2/14
5/24/22, 4:19 PM Build Your First Shiny Web App in R | by Chanin Nantasenamat | Towards Data Science

Why Build a Web App? Get started


Open in app

So the question is, why would you want to build a web application? That’s a great
question!

The deployed web application provides a graphical front-end (user interface or UI) that
allow users to enter input parameters that the back-end (the server) will process and send
back for display on the web front-end. In the context of machine learning, the deployment
of a trained machine learning model as a web application allow users to easily make
predictions by simply entering the input parameters into the form provided on the web
front-end that will serve as input features to the trained machine learning model where
the model will make a prediction.

All this at the convenience of a few clicks of the mouse as the user will not need to have
any technical knowledge in coding for making such prediction. In this article, you’ll be
learning how to make a web application in R using the Shiny package.

Aside from deploying machine learning models, web applications can be created to host
data-driven dashboard as well. These dashboards may provide useful summary data of
interest that can essentially be used for real-time monitoring and assessment of metrics
and performance.

What is Shiny?
Before we proceed further, perhaps a brief background about what exactly is Shiny.

Shiny is an R package that allows you to easily build interactive web applications. The
benefit of using Shiny is that it makes it possible to extend your R code to the web that
would essentially help to expand its usability to a wider community (i.e. from being used
by a single user to being used by hundreds or thousands of users via the internet).

Aside from the functionalities provided by the Shiny package, there are several extension
packages that supplements the functionality of Shiny such as shinythemes,
shinydashboard, shinyjs, etc.

What Can You Build with Shiny?


https://towardsdatascience.com/build-your-first-shiny-web-app-in-r-72f9538f9868 3/14
5/24/22, 4:19 PM Build Your First Shiny Web App in R | by Chanin Nantasenamat | Towards Data Science
What Can You Build with Shiny?
Open in app Get started

That’s a great question! The following are some starter ideas and I’m sure you can think of
several more.

Machine learning powered web application

Data-driven dashboards

Data collection forms

There are tons of additional examples at the Shiny Gallery.

Deploying the Web Application to the Internet


After testing the Shiny web apps on your own local computer and you are confident that it
works and are ready to publish to the internet you can deploy it onto your own server
(e.g. Digital Ocean) or via app hosting services such as Shinyapps.io and Heroku. So
what’s the difference between the two?

The benefit of having your own server is that you have total control on the computer and
as a result you can install all softwares, modules and packages to your heart’s content. The
downside of this is that you would need to have a great deal of knowledge to manage the
server. For example, you may need to be proficient in BASH commands in order to
manage a Ubuntu server on the cloud via service providers such as Digital Ocean ($100
Free Credit), Linode, Amazon Web Service or Google Cloud Platform.

The benefit of using an app hosting service is that you don’t have to worry about
managing a server. That’s right, no more dealing with server updates, no more
configuration of paths and complex compilation of softwares and libraries. These app
hosting service providers allows you to focus your energy on building the application,
period!

Structure of a Shiny Web App


The Shiny web app is comprised of 3 components:

https://towardsdatascience.com/build-your-first-shiny-web-app-in-r-72f9538f9868 4/14
5/24/22, 4:19 PM Build Your First Shiny Web App in R | by Chanin Nantasenamat | Towards Data Science

1. User interface (ui.R) — The UI is the frontend that accepts user input values.
Open in app Get started

2. Server function (server.R) — The Server is the backend that process these input
values to finally produce the output results that are finally displayed on the website.

3. shinyApp function — The app itself that combines the UI and server components
together.

Schematic illustration of how a Shiny web app works. (Drawn by Chanin Nantasenamat)

Code of the Shiny Web App


Now, comes the fun part and let’s have a look at the code of the Shiny web app that we are
going to be building today (shown below).

1 # Load R packages
2 library(shiny)
3 library(shinythemes)
4
5 # Define UI
6 ui <- fluidPage(theme = shinytheme("cerulean"),
7 navbarPage(
8
9 "My first app",
10 tabPanel("Navbar 1",
11 id b P l(
https://towardsdatascience.com/build-your-first-shiny-web-app-in-r-72f9538f9868 5/14
5/24/22, 4:19 PM Build Your First Shiny Web App in R | by Chanin Nantasenamat | Towards Data Science
11 sidebarPanel(
12 tags$h3("Input:"), Open in app Get started
13 textInput("txt1", "Given Name:", ""),
14 textInput("txt2", "Surname:", "")
15
16 ), # sidebarPanel
17 mainPanel(
18 h1("Header 1"),
19
20 h4("Output 1"),
21 verbatimTextOutput("txtout")
22 ) # mainPanel
23
24 ), # Navbar 1, tabPanel
25 tabPanel("Navbar 2", "This panel is intentionally left blank"),
26 tabPanel("Navbar 3", "This panel is intentionally left blank")
27
28 ) # navbarPage
29 ) # fluidPage
30
31 # Define server function
32 server <- function(input, output) {
33
34 output$txtout <- renderText({
35 paste( input$txt1, input$txt2, sep = " " )
36 })
37 }
38
39 # Create Shiny object
40 shinyApp(ui = ui, server = server)

shiny-first-app.R
hosted with ❤ by GitHub view raw

How Does the Shiny Web App Works?


A cartoon illustration of what is going on under the hood as we use the Shiny web app is
summarized below in 3 simple steps.

https://towardsdatascience.com/build-your-first-shiny-web-app-in-r-72f9538f9868 6/14
5/24/22, 4:19 PM Build Your First Shiny Web App in R | by Chanin Nantasenamat | Towards Data Science

Open in app Get started

Running the Shiny Web App


Now, let’s run the web application.

Step 1. Go ahead and fire up your RStudio.

Step 2. Click on File → New File → R Script and paste the entire block of code shown
above and save it as app.R (or you can download the app.R file).

Step 3. Click on the Run App button (shown below by the white circle below) that is
located at the top right of the File Panel.

https://towardsdatascience.com/build-your-first-shiny-web-app-in-r-72f9538f9868 7/14
5/24/22, 4:19 PM Build Your First Shiny Web App in R | by Chanin Nantasenamat | Towards Data Science

Open in app Get started

Screenshot of the app.R file containing the Shiny Web App inside RStudio.

After a few moments, you will see a pop-up window displaying the Shiny web app as
shown below. Notice that the web app has empty output value because the input
parameters are still empty.

https://towardsdatascience.com/build-your-first-shiny-web-app-in-r-72f9538f9868 8/14
5/24/22, 4:19 PM Build Your First Shiny Web App in R | by Chanin Nantasenamat | Towards Data Science

Open in app Get started

Screenshot of the executed app.R file (after hitting on the Run App button).

Let’s fill in the values into the two input box (Given Name and Surname) and you will see
that the Output box (the Main Panel) will now display the concatenated Given Name +
Surname. For example, we use “Machine” as the Given Name and “Learning” as the
Surname. Under the hood, the UI component accepts the input arguments from the 2 text
box for Given Name and Surname. Next, we concatenate the two variables to produce an
output of “Machine Learning”. Finally, the UI displays this output on the Main Panel (the
gray box).

https://towardsdatascience.com/build-your-first-shiny-web-app-in-r-72f9538f9868 9/14
5/24/22, 4:19 PM Build Your First Shiny Web App in R | by Chanin Nantasenamat | Towards Data Science

Open in app Get started

Screenshot of the web app with input parameters entered.

Line-by-Line Explanation of the Code


The code shown above has been commented to label the major sections of the code as
follows:

# Load R packages (Line 1),

# Define UI (Line 5),

# Define server function (Line 31)

# Create Shiny object (Line 39)

Now, we will be covering the above 4 sections in more depth in the forthcoming sub-
sections.

Load R packages (Lines 1–3)


Line 2 — Load the shiny package

Line 3 — Load the shinythemes package

Define UI (Lines 5–29)


Line 6 — The fluidPage() function creates fluid page layouts whereby the elements
can scale to occupy the available width of the browser. All UI elements are contained
within the fluidPage() function. The first input argument that we use is the theme

option where we define the use of the cerulean theme from the shinytheme R
package.

(Note: The closing parenthesis is on Line 29).

Line 7 — As the name implies, the navbarPage() function creates a page with a top
level navigation bar.

Line 9 — The name of the web app is defined to be “My first app” .

https://towardsdatascience.com/build-your-first-shiny-web-app-in-r-72f9538f9868 10/14
5/24/22, 4:19 PM Build Your First Shiny Web App in R | by Chanin Nantasenamat | Towards Data Science
e9 e a e o t e e app s de ed to e y st app .

Line 10 — Here we define the tab panel using the tabPanel() function.
Open in app This
Get started

represents the first of three tab panels and thus we define the tab panel to be “Navbar

1” .

Line 11 — Here we make use of the sidebarPanel() function (closing parenthesis is


on Line 16) so that the web app can have a sidebar panel on the left of the web app
that accepts user input parameters. Line 12 — The HTML tag tags$h3 is used to
provide the sidebar panel the subsubheading title of “Input:” .

Lines 13-14— The textInput() function is used to accept input values from users in
the form of a text field. The input arguments contained within the textInput()
function includes the (1) variable name (e.g. txt1 or txt2 ), (2) heading that is

displayed above the text field (e.g. “Given Name:” and “Surname:” ) and (3)

(Note: The closing parenthesis is on Line 28).

Line 17 — Here we make use of the mainPanel() function (closing parenthesis is on


Line 22).

Line 18 — Displays the heading of “Header 1” by using the h1() tag function.

Line 20 — Displays the subsubsubheading (not a typo but to signify the hierarchy of
the headings) of “Output1” by using the h4() tag function.

Line 21 — Displays the output value which is obtained by combining the input values
(Given Name and Surname) together.

Lines 25–26 — The two remaining tab panels are displayed via the tabPanel()

function on these 2 lines. The first input argument is the name of the tab panel which
is “Navbar 2” or “Navbar 3” while the second input argument is “This panel is

intentionally left blank” . As a result, upon clicking on these 2 tab panels we will see

the message “This panel is intentionally left blank” which are the content of
these 2 tab panels.

Define server function (Lines 31–37)


Line 32 — Defines the server whereby the input and output variables are essentially
connected via reactivity (i.e. changes in the input value will instantaneously or
reactively lead to updating of the output value).

Li 34 36 A h i h b
https://towardsdatascience.com/build-your-first-shiny-web-app-in-r-72f9538f9868 ill i i l i f 11/14
5/24/22, 4:19 PM Build Your First Shiny Web App in R | by Chanin Nantasenamat | Towards Data Science

Line 34–36 — As shown in the above cartoon illustration, input values coming from
Get started
input$txt1 and input$txt2 (i.e. corresponding to the GivenOpen
Namein app
and Surname ,

respectively) as entered by the user are assigned to the output$txtout variable (i.e.
the processed output value) that will be sent back to the UI for display in the Output
text box (Line 21). Particularly, the Given Name and Surname will be combined
together via the paste() function whereby the input arguments are the txt1 and
txt2 variables from the text input of UI (i.e. the input$txt1 and input$txt2 on Line
35)

Make note that output$txtout on Line 34–36 (from the Server function) is the same
variable as txtout on Line 21 (from the UI function). Likewise, txt1 and txt2 on Lines
13 and 14 (from the UI function) are the same variables as input$txt1 and
input$txt2 (from the Server function).

Create Shiny object (Lines 39–40)


Line 40 — The shinyApp() function takes as input argument the ui and server
variables defined above and fuses them together to build the actual Shiny web app
that we finally see.

Congratulations! You have now successfully created your very first Shiny
Web App in R!

Subscribe to my Mailing List for my best updates (and occasionally freebies) in Data Science!

About Me
I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and
Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a
YouTuber (AKA the Data Professor) making online videos about data science. In all
tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor
https://towardsdatascience.com/build-your-first-shiny-web-app-in-r-72f9538f9868 12/14
5/24/22, 4:19 PM Build Your First Shiny Web App in R | by Chanin Nantasenamat | Towards Data Science
, py (
GitHub page). Open in app Get started

Data Professor

Data Science, Machine Learning, Bioinformatics, Research and


Teaching are my passion. The Data Professor YouTube…

www.youtube.com

Connect with Me on Social Network


✅ YouTube: http://youtube.com/dataprofessor/

✅ Website: http://dataprofessor.org/ (Under construction)

✅ LinkedIn: https://www.linkedin.com/company/dataprofessor/

✅ Twitter: https://twitter.com/thedataprof

✅ FaceBook: http://facebook.com/dataprofessor/

✅ GitHub: https://github.com/dataprofessor/

✅ Instagram: https://www.instagram.com/data.professor/

Sign up for The Variable


By Towards Data Science

Every Thursday, the Variable delivers the very best of Towards Data Science: from hands-on tutorials
and cutting-edge research to original features you don't want to miss. Take a look.

Get this newsletter

https://towardsdatascience.com/build-your-first-shiny-web-app-in-r-72f9538f9868 13/14
5/24/22, 4:19 PM Build Your First Shiny Web App in R | by Chanin Nantasenamat | Towards Data Science

Open in app Get started

About Help Terms Privacy

Get the Medium app

https://towardsdatascience.com/build-your-first-shiny-web-app-in-r-72f9538f9868 14/14

You might also like