Shiny
Shiny
#shiny
Table of Contents
About 1
Remarks 2
Examples 2
Installation or Setup 2
Simple App 2
Including plots 4
Including tables 4
Chapter 2: How to write MCVE (Minimal, Complete, and Verifiable example) Shiny apps 6
Introduction 6
Examples 6
Basic structure 6
WRONG 7
RIGHT 7
Syntax 9
Examples 9
Introduction 11
Examples 11
reactive 11
eventReactive 12
reactiveValues 13
observeEvent 13
observe 14
Credits 18
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: shiny
It is an unofficial and free shiny ebook created for educational purposes. All the content is
extracted from Stack Overflow Documentation, which is written by many hardworking individuals at
Stack Overflow. It is neither affiliated with Stack Overflow nor official shiny.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to info@zzzprojects.com
https://riptutorial.com/ 1
Chapter 1: Getting started with shiny
Remarks
This section provides an overview of what shiny is, and why a developer might want to use it.
It should also mention any large subjects within shiny, and link out to the related topics. Since the
Documentation for shiny is new, you may need to create initial versions of those related topics.
Examples
Installation or Setup
Shiny can run as a standalone application on your local computer, on a server that can provide
shiny apps to multiple users (using shiny server), or on shinyapps.io.
1. I have some data analysis done on some data and have many 'non-coding' people on the
team, who have similar data like mine, and have similar analysis requirements. In such
cases, I can build a web application with shiny, which takes in user specific input data files,
and generate analyses.
2. I need to share analyzed data or relevant plots with others in the team. Shiny web apps can
be useful in such situations.
3. I don't have significant experience with web application programming, but need to quickly
assemble a simple interface. Shiny to the rescue with easy UI and server elements and
minimum coding.
4. Interactive elements allow your users to explore what element of the data is relevant to them.
For example, you could have data for the whole company loaded, but have a dropdown per
department like "Sales", "Production", "Finance" that can summarise the data the way the
users want to view it. The alternative would be producing a huge report pack with analyses
for each department, but they only read their chapter and the total.
Simple App
Each shiny app contains two parts: A user interface definition (UI) and a server script (server). This
example shows how you can print "Hello world" from UI or from server.
UI.R
https://riptutorial.com/ 2
In the UI you can place some view objects (div, inputs, buttons, etc).
library(shiny)
)
)
Server.R
In the server script you can define methods which manipulate data or listen to actions.
# Define server logic required to print "Hello World" when button is clicked
shinyServer(function(input, output) {
})
How to run?
1. Create two different files and place them into one directory, then use runApp('your dir path')
2. You can define two variables (ui and server, for example) and then use shinyApp(ui,server)
to run your app
Result
https://riptutorial.com/ 3
And after button click the server responds:
Including plots
The simplest way to include plots in your shinyApp is to use plotOutput in the ui and renderPlot in
the server. This will work with base graphics as well as ggPlots
library(shiny)
library(ggplot2)
ui <- fluidPage(
plotOutput('myPlot'),
plotOutput('myGgPlot')
)
shinyApp(ui, server)
Including tables
Tables are most easily included with the DT package, which is an R interface to the JavaScript
library DataTables.
library(shiny)
library(DT)
ui <- fluidPage(
dataTableOutput('myTable')
)
https://riptutorial.com/ 4
output$myTable <- renderDataTable({
datatable(iris)
})
}
shinyApp(ui, server)
https://riptutorial.com/ 5
Chapter 2: How to write MCVE (Minimal,
Complete, and Verifiable example) Shiny
apps
Introduction
If you are having issues with your Shiny apps, it is good practice to create an app that illustrates
your point. This app should be as simple as possible while still reflecting your problem. This
means using simple datasets, self-explanatory naming (especially for I/O IDs) and replacing plots
with simpler ones.
It is also advisable to create your MCVE in a way that as little non-standard libraries as possible
are required.
Examples
Basic structure
MCVE's should start the Shiny app when they are copied in the console. An easy way to do this is
using the shinyApp function. For example:
library(shiny)
ui <- fluidPage(
checkboxInput('checkbox', 'click me'),
verbatimTextOutput('text')
)
shinyApp(ui, server)
library(shiny)
shinyApp(
fluidPage(
checkboxInput('checkbox', 'click me'),
verbatimTextOutput('text')
),
https://riptutorial.com/ 6
function(input, output, session){
output$text <- renderText({
isolate(input$checkbox)
})
}
)
shinyApp(ui, server)
In practice, shiny Apps are often very complicated and full of features that have been developed
over time. More often than not, those additional details are not necessary to reproduce your issue.
It is best if you skip such details when writing MCVE's.
WRONG
Why is my plot not showing?
library(shiny)
library(ggplot2)
ui <- fluidPage(
plotOutput('plot')
)
shinyApp(ui, server)
RIGHT
Why is my Plot not showing?
library(shiny)
library(ggplot2)
ui <- fluidPage(
plotOutput('plot')
https://riptutorial.com/ 7
)
shinyApp(ui, server)
Read How to write MCVE (Minimal, Complete, and Verifiable example) Shiny apps online:
https://riptutorial.com/shiny/topic/10653/how-to-write-mcve--minimal--complete--and-verifiable-
example--shiny-apps
https://riptutorial.com/ 8
Chapter 3: Javascript API
Syntax
• session$sendCustomMessage(name,list of parameters)
• Shiny.addCustomMessageHandler(name, JS function that accepts list of parameters)
• Shiny.onInputChange(name,value)
Examples
Sending data from server to client
In many instances, you will want to send data from the R server to the JS client. Here is a very
simple example:
library(shiny)
runApp(
list(
ui = fluidPage(
tags$script(
"Shiny.addCustomMessageHandler('message', function(params) { alert(params); });"
),
actionButton("btn","Press Me")
),
server = function(input, output, session) {
observeEvent(input$btn,{
randomNumber <- runif(1,0,100)
session$sendCustomMessage("message",list(paste0(randomNumber," is a random number!")))
})
}
)
)
The session$sendCustomMessage function lets you send parameters from R to a javascript function,
and Shiny.addCustomMessageHandler let's you define the javascript function that accepts the
parameters from R.
Note: Lists are converted to JSON when they are passed from R to javascript
In some instances, you will want to send data from JS client to the R server. Here is a basic
example using javascript's Shiny.onInputChange function:
library(shiny)
runApp(
https://riptutorial.com/ 9
list(
ui = fluidPage(
# create password input
HTML('<input type="password" id="passwordInput">'),
# use jquery to write function that sends value to
# server when changed
tags$script(
'$("#passwordInput").on("change",function() {
Shiny.onInputChange("myInput",this.value);
})'
),
# show password
verbatimTextOutput("test")
),
server = function(input, output, session) {
# read in then show password
output$test <- renderPrint(
input$myInput
)
}
)
)
Here we create a password input with id passwordInput. We add a Javascript function on the UI that
reacts to changes in passwordInput, and sends the value to the server using Shiny.onInputChange.
Shiny.onInputChange takes two parameters, a name for the input$*name*, plus a value for
input$*name*
Then you can use input$*name* like any other Shiny input.
https://riptutorial.com/ 10
Chapter 4: reactive, reactiveValue and
eventReactive, observe and observeEvent in
Shiny
Introduction
reactive, reactiveValue and eventReactive are various kinds of reactive expressions in Shiny.
They yield output which can be used as input in other expressions, which will in turn take a
dependency on the reactive expression.
observe and observeEvent are similar to reactive expressions. The big difference is that the
observers do not yield any output and thus they are only useful for their side effects.
Examples
reactive
A reactive can be used to make output depend on another expression. In the example below, the
output$text element is dependent on text_reactive, which in turn is dependent on input$user_text.
Whenever input$user_text changes, output$text element and text_reactive become invalidated.
They are recalculated based on the new value for input$user_text.
library(shiny)
ui <- fluidPage(
headerPanel("Example reactive"),
mainPanel(
# input field
textInput("user_text", label = "Enter some text:", placeholder = "Please enter some
text."),
# reactive expression
text_reactive <- reactive({
input$user_text
})
# text output
output$text <- renderText({
https://riptutorial.com/ 11
text_reactive()
})
}
eventReactive
eventReactive( event {
code to run
})
eventReactives are not dependent on all reactive expressions in their body ('code to run' in the
snippet above). Instead, they are only dependent on the expressions specified in the event
section.
In the example below, we have added a submit button, and created an eventReactive. Whenever
input$user_text changes, the eventReactive is not invalidated, since the eventReactive is only
dependent on the actionButton input$submit. Whenever that button is pressed, text_reactive and
subsequently output$text are invalidated, and will be recalulated based on the updated
input$user_text.
library(shiny)
ui <- fluidPage(
headerPanel("Example eventReactive"),
mainPanel(
# input field
textInput("user_text", label = "Enter some text:", placeholder = "Please enter some
text."),
# submit button
actionButton("submit", label = "Submit"),
# reactive expression
text_reactive <- eventReactive( input$submit, {
input$user_text
})
# text output
output$text <- renderText({
text_reactive()
})
}
https://riptutorial.com/ 12
shinyApp(ui = ui, server = server)
reactiveValues
reactiveValues can be used to store objects, to which other expressions can take a dependency.
In the example below, a reactiveValues object is initialized with value "No text has been submitted
yet.". A separate observer is created to update the reactiveValues object whenever the submit
button is pressed. Note that the reactiveValues itself does not take a dependency on the
expressions in its body.
library(shiny)
ui <- fluidPage(
headerPanel("Example reactiveValues"),
mainPanel(
# input field
textInput("user_text", label = "Enter some text:", placeholder = "Please enter some
text."),
actionButton("submit", label = "Submit"),
# reactiveValues
text_reactive <- reactiveValues(
text = "No text has been submitted yet."
)
# text output
output$text <- renderText({
text_reactive$text
})
}
observeEvent
An observeEvent object can be used to trigger a piece of code when a certain event occurs. It is
constructed as:
observeEvent( event {
code to run
https://riptutorial.com/ 13
})
The observeEvent will only be dependent on the 'event' section in the small piece of code above. It
will not be dependent on anything in the 'code to run' part. An example implementation can be
found below:
library(shiny)
ui <- fluidPage(
headerPanel("Example reactive"),
mainPanel(
# action buttons
actionButton("button1","Button 1"),
actionButton("button2","Button 2")
)
)
observe
An observe expression is triggered every time one of its inputs changes. The major difference with
regards to a reactive expression is that it yields no output, and it should only be used for its side
effects (such as modifying a reactiveValues object, or triggering a pop-up).
Also, note that observe does not ignore NULL's, therefore it will fire even if its inputs are still
NULL. observeEvent by default does ignore NULL, as is almost always desirable.
library(shiny)
ui <- fluidPage(
headerPanel("Example reactive"),
mainPanel(
# action buttons
actionButton("button1","Button 1"),
actionButton("button2","Button 2")
)
)
https://riptutorial.com/ 14
server <- function(input, output) {
Read reactive, reactiveValue and eventReactive, observe and observeEvent in Shiny online:
https://riptutorial.com/shiny/topic/10787/reactive--reactivevalue-and-eventreactive--observe-and-
observeevent-in-shiny
https://riptutorial.com/ 15
Chapter 5: Upload Data to shiny
Examples
Upload .RData Files to shiny with fileInput()
The example allows you to upload .RData files. The approach with load and get allows you to
assign the loaded data to a variable name of your choice. For the matter of the example being
"standalone" I inserted the top section that stores two vectors to your disk in order to load and plot
them later.
library(shiny)
# Define UI
ui <- shinyUI(fluidPage(
titlePanel(".RData File Upload Test"),
mainPanel(
fileInput("file", label = ""),
actionButton(inputId="plot","Plot"),
plotOutput("hist"))
)
)
observeEvent(input$plot,{
if ( is.null(input$file)) return(NULL)
inFile <- input$file
file <- inFile$datapath
# load the file into new environment and get it from there
e = new.env()
name <- load(file, envir = e)
data <- e[[name]]
https://riptutorial.com/ 16
It is also possible to have an user upload csv's to your Shiny app. The code below shows a small
example on how this can be achieved. It also includes a radioButton input so the user can
interactively choose the separator to be used.
library(shiny)
library(DT)
# Define UI
ui <- shinyUI(fluidPage(
output$sample_table<- DT::renderDataTable({
df <- df_products_upload()
DT::datatable(df)
})
}
)
https://riptutorial.com/ 17
Credits
S.
Chapters Contributors
No
Getting started with Batanichek, Bogdan Rau, chrki, Community, Florian, Gregor de
1
shiny Cillia, jsb, Mathias711, micstr, sigmabeta
reactive,
reactiveValue and
eventReactive,
4 Florian
observe and
observeEvent in
Shiny
https://riptutorial.com/ 18