SlideShare a Scribd company logo
1 of 17
R Shiny
An Introduction to
Making an Interactive
Web Application
Chloe Thomas
ScHARR, University of Sheffield
What is R shiny?
How does it work?
Do I need to know how to code in HTML?
Where can I get more information?
A web application framework for R that allows you to turn your
data into an interactive web App.
Shiny apps have two components:
- user interface script (controls layout and appearance by
converting R code into HTML)
- server script (contains the code needed to build the app)
No knowledge of HTML, JavaScript or CSS is required. However, you
can make your apps more interesting if you know some HTML.
There are some excellent tutorials and lots of links to more
information at http://shiny.rstudio.com/
Getting Started
> install.packages("shiny")
> library(shiny)
> runApp("my_app")
As a minimum, every shiny app has two R scripts (named ui and server) saved
within the same directory (e.g. “my_app”).
ui.R
server.R
Other scripts (written in standard R code), libraries and data can be called by the
server script if they are needed, using standard R commands above the shinyServer
function.
shinyUI(fluidPage(
))
shinyServer(function(input, output) {
})
The fluidPage function allows the display to
adjust automatically to the browser dimensions.
The unnamed function contains
the code needed to run the app.
The User Interface (ui.R)
# ui.R
shinyUI(fluidPage(
titlePanel("title panel"),
sidebarLayout(position = "right",
sidebarPanel( "sidebar panel"),
mainPanel("main panel")
)
))
A series of nested shiny
functions control the
layout of the content.
sidebarLayout is a
function with two
compulsory arguments,
both themselves functions
(sidebarPanel and
mainPanel). An optional
argument controls the
position of the panels.
Text is written as a
character string inside
quotation marks.
absolutePanel (fixedPanel) Panel with absolute positioning
bootstrapPage (basicPage) Create a Bootstrap page
column
Create a column within a UI
definition
conditionalPanel Conditional Panel
fixedPage (fixedRow)
Create a page with a fixed
layout
fluidPage (fluidRow) Create a page with fluid layout
headerPanel Create a header panel
helpText Create a help text element
icon Create an icon
mainPanel Create a main panel
navbarPage (navbarMenu)
Create a page with a top level
navigation bar
navlistPanel Create a navigation list panel
pageWithSidebar Create a page with a sidebar
sidebarLayout Layout a sidebar and main area
sidebarPanel Create a sidebar panel
tabPanel Create a tab panel
tabsetPanel Create a tabset panel
titlePanel
Create a panel containing an
application title.
inputPanel Input panel
flowLayout Flow layout
splitLayout Split layout
verticalLayout Lay out UI elements vertically
wellPanel Create a well panel
withMathJax
Load the MathJax library and
typeset math expressions
Shiny User Interface Functions
Formatting Text
To make things look a bit more interesting there are lots of shiny commands that can
alter the text colour, style and size. Alternatively, if you are familiar with HTML, you
can write HTML code directly inside HTML("").
shiny function HTML5 equivalent Creates
p <p> A paragraph of text
h1 <h1> A first level header
h2 <h2> A second level header
h3 <h3> A third level header
h4 <h4> A fourth level header
h5 <h5> A fifth level header
h6 <h6> A sixth level header
a <a> A hyper link
br <br> A line break (e.g. a blank line)
div <div> A division of text with a uniform style
span <span>
An in-line division of text with a
uniform style
pre <pre> Text ‘as is’ in a fixed width font
code <code> A formatted block of code
img <img> An image
strong <strong> Bold text
em <em> Italicized text
HTML
Directly passes a character string as
HTML code
Adding Images
# ui.R
shinyUI(fluidPage(
titlePanel("My Shiny App"),
sidebarLayout(
sidebarPanel(),
mainPanel(
img(src = “my_image.png", height = 400, width = 400)
)
)
))
The image file must be placed inside a folder
named www within the same directory as the
ui and server scripts. Any file placed in the
www folder will be shared with the web
browser.
Adding Widgets
Widgets are interactive web elements. A series of inbuild shiny functions allows widgets
to be easily added to webpages. Each function has several arguments. It must have at
least a name (used to access its value, but not visible) and a label (visible on the page).
Both are character strings. Other arguments are widget specific.
# ui.R
shinyUI(fluidPage(
titlePanel("Basic widgets"),
fluidRow(
column(3,
h3("Buttons"),
actionButton("action", label = "Action"),
br(),
br(),
submitButton("Submit")),
column(3,
h3("Single checkbox"),
checkboxInput("checkbox", label = "Choice A", value = TRUE)),
column(3,
checkboxGroupInput("checkGroup",
label = h3("Checkbox group"),
choices = list("Choice 1" = 1, "Choice 2" = 2, "Choice 3" = 3),
selected = 1)),
column(3,
dateInput("date",
label = h3("Date input"),
value = "2014-01-01"))
)
))
Adding Widgets Action
button
Submit
button
Single
checkbox
(whether
pre-selected)
Checkbox
group (list
choices and
which pre-
selected)
Date input
Adding Reactive Output
Widgets allow users to input their choices. Reactive output is a response to those choices.
Programming it into an app is a two-step process:
- Add an R object to the user interface to indicate where it should be displayed.
- Add instructions on how to build the object in the server
Output function creates
htmlOutput raw HTML
imageOutput image
plotOutput plot
tableOutput table
textOutput text
# ui.R
shinyUI(fluidPage(
titlePanel("My Shiny App"),
sidebarLayout(
sidebarPanel(
sliderInput(“value",
label = “Value of interest:",
min = 0, max = 100, value = 50)
),
mainPanel(
textOutput("text1")
)
)
))
Output functions have one argument,
which is a name (character string). In
this case “text1”. This is used in the
server to identify the output.
Adding Reactive Output
The unnamed function inside shinyServer contains all the code that needs to be
updated when a user accesses the app. All R output objects used in the ui need to be
defined in server using the prefix output$ followed by the name of the object.
e.g. output$text1
The element should be defined using one of the shiny render* functions – this should
be chosen to reflect the type of output. Each render function takes a single argument
(R expression) surrounded by braces.
# server.R
shinyServer(function(input, output) {
output$text1 <- renderText({
"You have selected" , input$value)
})
}
)
render function creates
renderImage
images (saved as a
link to a source file)
renderPlot plots
renderPrint any printed output
renderTable
data frame, matrix,
other table like
structures
renderText character strings
renderUI
a Shiny tag object or
HTML
The Server
The server is where all the code is located for execution of the app. How frequently
code is run depends upon where it is placed within the server script.
Code placed here will be run once
when the app is launched.
shinyServer will be executed and the
unnamed function saved. Good
place to source other scripts, read
data sets and load libraries.
Code placed here will run once each
time a new user visits the app. The
unnamed function will run once and
save a distinct set of reactive objects
for each user. Good place to put
objects that record a user’s session.
Code placed here will run every
time the user changes the widget
that this particular output depends
upon. Important to not put
unnecessary code here as it will
slow down the entire app.
Example of a shiny app with code
More complex shiny functions
Reactive Expressions
Like render functions but they allow you to decide which parts of the app update when,
for more streamlined computation.
Absolute Positioning
Allows personalisation of the user interface of the app using a grid based system.
Interactive Visualisations
Allows you to make interactive maps and charts using JavaScript libraries like Google
Charts, Leaflet and d3.
Progress Bars
So users know that something is happening whilst waiting for a calculation to complete.
Integration with R Markdown
To make interactive documents.
Shiny Server Pro (not free)
Allows user authentication and personalisation of user interface.
A slightly more complex shiny app
Sharing apps
Two main options: 1) Share the files with users that have R and know how to use it.
(e.g. email zip file directly, use GitHub to share files, run from a
web-link - runURl(“<the weblink>”)).
2) Share it as a web page.
Host an app yourself
e.g. For University of Sheffield apps, go through CICs - £100 per year for hosting on a
virtual server.
Shinyapps.io
Rstudio’s cloud hosting service for shiny apps. Four different levels of service, including a
free service (max 5 apps and 25 active hours per month). You retain complete control
over your app.
Shiny Server
A free downloadable programme that can be run on Linux servers. Shiny Server Pro is a
paid professional version that includes password authentification, administrator tools and
email support (starts at >$10,000 per year.)
General Comments
Shiny takes a bit of getting used to, but the tutorials give an excellent
introduction and there is lots of help online.
Really quick way of visually presenting your data interactively – great for
impact and engagement with the general public/customers/clients.
Can be frustrating switching between server and ui scripts when writing
reactive output. However, apparently now these can be combined into a
single script.
Can also be very frustrating when usual R commands don’t work the way you
might expect them to in the server.
Problems arise when trying to do more complicated things. A particular issue
is needing to create input that is itself reactive to other input – this is possible
but not straightforward.
Might not be the best solution if you want a professional looking app, with
complex functionality.
Shiny is still in development and if something doesn’t seem possible, it may
be worth contacting the developers and seeing whether they can help you.

More Related Content

What's hot

[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
洪 鹏发
 

What's hot (20)

Apache Spark Introduction
Apache Spark IntroductionApache Spark Introduction
Apache Spark Introduction
 
Web Development with HTML5, CSS3 & JavaScript
Web Development with HTML5, CSS3 & JavaScriptWeb Development with HTML5, CSS3 & JavaScript
Web Development with HTML5, CSS3 & JavaScript
 
Nextjs13.pptx
Nextjs13.pptxNextjs13.pptx
Nextjs13.pptx
 
Dynamic HTML (DHTML)
Dynamic HTML (DHTML)Dynamic HTML (DHTML)
Dynamic HTML (DHTML)
 
Introduction to Django REST Framework, an easy way to build REST framework in...
Introduction to Django REST Framework, an easy way to build REST framework in...Introduction to Django REST Framework, an easy way to build REST framework in...
Introduction to Django REST Framework, an easy way to build REST framework in...
 
Presentation of bootstrap
Presentation of bootstrapPresentation of bootstrap
Presentation of bootstrap
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
HTML Fundamentals
HTML FundamentalsHTML Fundamentals
HTML Fundamentals
 
Introduction to ajax
Introduction  to  ajaxIntroduction  to  ajax
Introduction to ajax
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Data visualization & Story Telling with Data
Data visualization & Story Telling with DataData visualization & Story Telling with Data
Data visualization & Story Telling with Data
 
Web Development using HTML & CSS
Web Development using HTML & CSSWeb Development using HTML & CSS
Web Development using HTML & CSS
 
Introduction to Web Development
Introduction to Web DevelopmentIntroduction to Web Development
Introduction to Web Development
 
HTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts BasicsHTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts Basics
 
Bootstrap ppt
Bootstrap pptBootstrap ppt
Bootstrap ppt
 
Big Data and Hadoop Guide
Big Data and Hadoop GuideBig Data and Hadoop Guide
Big Data and Hadoop Guide
 
Web Development
Web DevelopmentWeb Development
Web Development
 
Introducing Neo4j
Introducing Neo4jIntroducing Neo4j
Introducing Neo4j
 
Html form tag
Html form tagHtml form tag
Html form tag
 
Data Visualisation & Analytics with Tableau (Beginner) - by Maria Koumandraki
Data Visualisation & Analytics with Tableau (Beginner) - by Maria KoumandrakiData Visualisation & Analytics with Tableau (Beginner) - by Maria Koumandraki
Data Visualisation & Analytics with Tableau (Beginner) - by Maria Koumandraki
 

Similar to Introduction to Shiny for building web apps in R

Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)
pbarasia
 

Similar to Introduction to Shiny for building web apps in R (20)

As pnet
As pnetAs pnet
As pnet
 
WEB DEVELOPMENT
WEB DEVELOPMENTWEB DEVELOPMENT
WEB DEVELOPMENT
 
shiny.pdf
shiny.pdfshiny.pdf
shiny.pdf
 
Atlas Php
Atlas PhpAtlas Php
Atlas Php
 
Asp.net
Asp.netAsp.net
Asp.net
 
R-Shiny Cheat sheet
R-Shiny Cheat sheetR-Shiny Cheat sheet
R-Shiny Cheat sheet
 
ArduinoWorkshop2.pdf
ArduinoWorkshop2.pdfArduinoWorkshop2.pdf
ArduinoWorkshop2.pdf
 
Building interactive web app with shiny
Building interactive web app with shinyBuilding interactive web app with shiny
Building interactive web app with shiny
 
Lecture-15.pptx
Lecture-15.pptxLecture-15.pptx
Lecture-15.pptx
 
Web development intership Presentation.pptx
Web development intership Presentation.pptxWeb development intership Presentation.pptx
Web development intership Presentation.pptx
 
Front-end. Global domination
Front-end. Global dominationFront-end. Global domination
Front-end. Global domination
 
Frontend. Global domination.
Frontend. Global domination.Frontend. Global domination.
Frontend. Global domination.
 
Build web apps with R
Build web apps with RBuild web apps with R
Build web apps with R
 
Ruby On Rails Siddhesh
Ruby On Rails SiddheshRuby On Rails Siddhesh
Ruby On Rails Siddhesh
 
Php
PhpPhp
Php
 
Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)
 
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for DevelopersMSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
 
Android Deep Dive
Android Deep DiveAndroid Deep Dive
Android Deep Dive
 
Diving deep in compose.pdf
Diving deep in compose.pdfDiving deep in compose.pdf
Diving deep in compose.pdf
 
A intro to (hosted) Shiny Apps
A intro to (hosted) Shiny AppsA intro to (hosted) Shiny Apps
A intro to (hosted) Shiny Apps
 

More from Paul Richards

More from Paul Richards (12)

Sheffield_R_ July meeting - Interacting with R - IDEs, Git and workflow
Sheffield_R_ July meeting - Interacting with R - IDEs, Git and workflowSheffield_R_ July meeting - Interacting with R - IDEs, Git and workflow
Sheffield_R_ July meeting - Interacting with R - IDEs, Git and workflow
 
SheffieldR July Meeting - Multiple Imputation with Chained Equations (MICE) p...
SheffieldR July Meeting - Multiple Imputation with Chained Equations (MICE) p...SheffieldR July Meeting - Multiple Imputation with Chained Equations (MICE) p...
SheffieldR July Meeting - Multiple Imputation with Chained Equations (MICE) p...
 
Preparing and submitting a package to CRAN - June Sanderson, Sheffield R User...
Preparing and submitting a package to CRAN - June Sanderson, Sheffield R User...Preparing and submitting a package to CRAN - June Sanderson, Sheffield R User...
Preparing and submitting a package to CRAN - June Sanderson, Sheffield R User...
 
How to win $10m - analysing DOTA2 data in R (Sheffield R Users Group - May)
How to win $10m - analysing DOTA2 data in R (Sheffield R Users Group - May)How to win $10m - analysing DOTA2 data in R (Sheffield R Users Group - May)
How to win $10m - analysing DOTA2 data in R (Sheffield R Users Group - May)
 
Introduction to knitr - May Sheffield R Users group
Introduction to knitr - May Sheffield R Users groupIntroduction to knitr - May Sheffield R Users group
Introduction to knitr - May Sheffield R Users group
 
Querying open data with R - Talk at April SheffieldR Users Gp
Querying open data with R - Talk at April SheffieldR Users GpQuerying open data with R - Talk at April SheffieldR Users Gp
Querying open data with R - Talk at April SheffieldR Users Gp
 
OrienteeRing - using R to optimise mini mountain marathon routes - Pete Dodd ...
OrienteeRing - using R to optimise mini mountain marathon routes - Pete Dodd ...OrienteeRing - using R to optimise mini mountain marathon routes - Pete Dodd ...
OrienteeRing - using R to optimise mini mountain marathon routes - Pete Dodd ...
 
Phylogeny in R - Bianca Santini Sheffield R Users March 2015
Phylogeny in R - Bianca Santini Sheffield R Users March 2015Phylogeny in R - Bianca Santini Sheffield R Users March 2015
Phylogeny in R - Bianca Santini Sheffield R Users March 2015
 
Intro to ggplot2 - Sheffield R Users Group, Feb 2015
Intro to ggplot2 - Sheffield R Users Group, Feb 2015Intro to ggplot2 - Sheffield R Users Group, Feb 2015
Intro to ggplot2 - Sheffield R Users Group, Feb 2015
 
Sheffield R Jan 2015 - Using R to investigate parasite infections in Asian el...
Sheffield R Jan 2015 - Using R to investigate parasite infections in Asian el...Sheffield R Jan 2015 - Using R to investigate parasite infections in Asian el...
Sheffield R Jan 2015 - Using R to investigate parasite infections in Asian el...
 
Introduction to data.table in R
Introduction to data.table in RIntroduction to data.table in R
Introduction to data.table in R
 
Dplyr and Plyr
Dplyr and PlyrDplyr and Plyr
Dplyr and Plyr
 

Recently uploaded

Jax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckJax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined Deck
Marc Lester
 

Recently uploaded (20)

Microsoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMicrosoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdf
 
Abortion Clinic In Polokwane ](+27832195400*)[ 🏥 Safe Abortion Pills in Polok...
Abortion Clinic In Polokwane ](+27832195400*)[ 🏥 Safe Abortion Pills in Polok...Abortion Clinic In Polokwane ](+27832195400*)[ 🏥 Safe Abortion Pills in Polok...
Abortion Clinic In Polokwane ](+27832195400*)[ 🏥 Safe Abortion Pills in Polok...
 
OpenChain Webinar: AboutCode and Beyond - End-to-End SCA
OpenChain Webinar: AboutCode and Beyond - End-to-End SCAOpenChain Webinar: AboutCode and Beyond - End-to-End SCA
OpenChain Webinar: AboutCode and Beyond - End-to-End SCA
 
Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...
Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...
Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...
 
Lessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfLessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdf
 
How to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabberHow to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabber
 
The Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test AutomationThe Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test Automation
 
Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...
Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...
Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
 
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-CloudAlluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
 
OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024
 
Evolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI EraEvolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI Era
 
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
 
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
 
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
 
Optimizing Operations by Aligning Resources with Strategic Objectives Using O...
Optimizing Operations by Aligning Resources with Strategic Objectives Using O...Optimizing Operations by Aligning Resources with Strategic Objectives Using O...
Optimizing Operations by Aligning Resources with Strategic Objectives Using O...
 
Jax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckJax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined Deck
 
Transformer Neural Network Use Cases with Links
Transformer Neural Network Use Cases with LinksTransformer Neural Network Use Cases with Links
Transformer Neural Network Use Cases with Links
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
 
Weeding your micro service landscape.pdf
Weeding your micro service landscape.pdfWeeding your micro service landscape.pdf
Weeding your micro service landscape.pdf
 

Introduction to Shiny for building web apps in R

  • 1. R Shiny An Introduction to Making an Interactive Web Application Chloe Thomas ScHARR, University of Sheffield
  • 2. What is R shiny? How does it work? Do I need to know how to code in HTML? Where can I get more information? A web application framework for R that allows you to turn your data into an interactive web App. Shiny apps have two components: - user interface script (controls layout and appearance by converting R code into HTML) - server script (contains the code needed to build the app) No knowledge of HTML, JavaScript or CSS is required. However, you can make your apps more interesting if you know some HTML. There are some excellent tutorials and lots of links to more information at http://shiny.rstudio.com/
  • 3. Getting Started > install.packages("shiny") > library(shiny) > runApp("my_app") As a minimum, every shiny app has two R scripts (named ui and server) saved within the same directory (e.g. “my_app”). ui.R server.R Other scripts (written in standard R code), libraries and data can be called by the server script if they are needed, using standard R commands above the shinyServer function. shinyUI(fluidPage( )) shinyServer(function(input, output) { }) The fluidPage function allows the display to adjust automatically to the browser dimensions. The unnamed function contains the code needed to run the app.
  • 4. The User Interface (ui.R) # ui.R shinyUI(fluidPage( titlePanel("title panel"), sidebarLayout(position = "right", sidebarPanel( "sidebar panel"), mainPanel("main panel") ) )) A series of nested shiny functions control the layout of the content. sidebarLayout is a function with two compulsory arguments, both themselves functions (sidebarPanel and mainPanel). An optional argument controls the position of the panels. Text is written as a character string inside quotation marks.
  • 5. absolutePanel (fixedPanel) Panel with absolute positioning bootstrapPage (basicPage) Create a Bootstrap page column Create a column within a UI definition conditionalPanel Conditional Panel fixedPage (fixedRow) Create a page with a fixed layout fluidPage (fluidRow) Create a page with fluid layout headerPanel Create a header panel helpText Create a help text element icon Create an icon mainPanel Create a main panel navbarPage (navbarMenu) Create a page with a top level navigation bar navlistPanel Create a navigation list panel pageWithSidebar Create a page with a sidebar sidebarLayout Layout a sidebar and main area sidebarPanel Create a sidebar panel tabPanel Create a tab panel tabsetPanel Create a tabset panel titlePanel Create a panel containing an application title. inputPanel Input panel flowLayout Flow layout splitLayout Split layout verticalLayout Lay out UI elements vertically wellPanel Create a well panel withMathJax Load the MathJax library and typeset math expressions Shiny User Interface Functions
  • 6. Formatting Text To make things look a bit more interesting there are lots of shiny commands that can alter the text colour, style and size. Alternatively, if you are familiar with HTML, you can write HTML code directly inside HTML(""). shiny function HTML5 equivalent Creates p <p> A paragraph of text h1 <h1> A first level header h2 <h2> A second level header h3 <h3> A third level header h4 <h4> A fourth level header h5 <h5> A fifth level header h6 <h6> A sixth level header a <a> A hyper link br <br> A line break (e.g. a blank line) div <div> A division of text with a uniform style span <span> An in-line division of text with a uniform style pre <pre> Text ‘as is’ in a fixed width font code <code> A formatted block of code img <img> An image strong <strong> Bold text em <em> Italicized text HTML Directly passes a character string as HTML code
  • 7. Adding Images # ui.R shinyUI(fluidPage( titlePanel("My Shiny App"), sidebarLayout( sidebarPanel(), mainPanel( img(src = “my_image.png", height = 400, width = 400) ) ) )) The image file must be placed inside a folder named www within the same directory as the ui and server scripts. Any file placed in the www folder will be shared with the web browser.
  • 8. Adding Widgets Widgets are interactive web elements. A series of inbuild shiny functions allows widgets to be easily added to webpages. Each function has several arguments. It must have at least a name (used to access its value, but not visible) and a label (visible on the page). Both are character strings. Other arguments are widget specific.
  • 9. # ui.R shinyUI(fluidPage( titlePanel("Basic widgets"), fluidRow( column(3, h3("Buttons"), actionButton("action", label = "Action"), br(), br(), submitButton("Submit")), column(3, h3("Single checkbox"), checkboxInput("checkbox", label = "Choice A", value = TRUE)), column(3, checkboxGroupInput("checkGroup", label = h3("Checkbox group"), choices = list("Choice 1" = 1, "Choice 2" = 2, "Choice 3" = 3), selected = 1)), column(3, dateInput("date", label = h3("Date input"), value = "2014-01-01")) ) )) Adding Widgets Action button Submit button Single checkbox (whether pre-selected) Checkbox group (list choices and which pre- selected) Date input
  • 10. Adding Reactive Output Widgets allow users to input their choices. Reactive output is a response to those choices. Programming it into an app is a two-step process: - Add an R object to the user interface to indicate where it should be displayed. - Add instructions on how to build the object in the server Output function creates htmlOutput raw HTML imageOutput image plotOutput plot tableOutput table textOutput text # ui.R shinyUI(fluidPage( titlePanel("My Shiny App"), sidebarLayout( sidebarPanel( sliderInput(“value", label = “Value of interest:", min = 0, max = 100, value = 50) ), mainPanel( textOutput("text1") ) ) )) Output functions have one argument, which is a name (character string). In this case “text1”. This is used in the server to identify the output.
  • 11. Adding Reactive Output The unnamed function inside shinyServer contains all the code that needs to be updated when a user accesses the app. All R output objects used in the ui need to be defined in server using the prefix output$ followed by the name of the object. e.g. output$text1 The element should be defined using one of the shiny render* functions – this should be chosen to reflect the type of output. Each render function takes a single argument (R expression) surrounded by braces. # server.R shinyServer(function(input, output) { output$text1 <- renderText({ "You have selected" , input$value) }) } ) render function creates renderImage images (saved as a link to a source file) renderPlot plots renderPrint any printed output renderTable data frame, matrix, other table like structures renderText character strings renderUI a Shiny tag object or HTML
  • 12. The Server The server is where all the code is located for execution of the app. How frequently code is run depends upon where it is placed within the server script. Code placed here will be run once when the app is launched. shinyServer will be executed and the unnamed function saved. Good place to source other scripts, read data sets and load libraries. Code placed here will run once each time a new user visits the app. The unnamed function will run once and save a distinct set of reactive objects for each user. Good place to put objects that record a user’s session. Code placed here will run every time the user changes the widget that this particular output depends upon. Important to not put unnecessary code here as it will slow down the entire app.
  • 13. Example of a shiny app with code
  • 14. More complex shiny functions Reactive Expressions Like render functions but they allow you to decide which parts of the app update when, for more streamlined computation. Absolute Positioning Allows personalisation of the user interface of the app using a grid based system. Interactive Visualisations Allows you to make interactive maps and charts using JavaScript libraries like Google Charts, Leaflet and d3. Progress Bars So users know that something is happening whilst waiting for a calculation to complete. Integration with R Markdown To make interactive documents. Shiny Server Pro (not free) Allows user authentication and personalisation of user interface.
  • 15. A slightly more complex shiny app
  • 16. Sharing apps Two main options: 1) Share the files with users that have R and know how to use it. (e.g. email zip file directly, use GitHub to share files, run from a web-link - runURl(“<the weblink>”)). 2) Share it as a web page. Host an app yourself e.g. For University of Sheffield apps, go through CICs - £100 per year for hosting on a virtual server. Shinyapps.io Rstudio’s cloud hosting service for shiny apps. Four different levels of service, including a free service (max 5 apps and 25 active hours per month). You retain complete control over your app. Shiny Server A free downloadable programme that can be run on Linux servers. Shiny Server Pro is a paid professional version that includes password authentification, administrator tools and email support (starts at >$10,000 per year.)
  • 17. General Comments Shiny takes a bit of getting used to, but the tutorials give an excellent introduction and there is lots of help online. Really quick way of visually presenting your data interactively – great for impact and engagement with the general public/customers/clients. Can be frustrating switching between server and ui scripts when writing reactive output. However, apparently now these can be combined into a single script. Can also be very frustrating when usual R commands don’t work the way you might expect them to in the server. Problems arise when trying to do more complicated things. A particular issue is needing to create input that is itself reactive to other input – this is possible but not straightforward. Might not be the best solution if you want a professional looking app, with complex functionality. Shiny is still in development and if something doesn’t seem possible, it may be worth contacting the developers and seeing whether they can help you.