You are on page 1of 2

Shiny : : CHEAT SHEET

Basics Building an App Complete the template by adding arguments to fluidPage() and a
body to the server function. Inputs
A Shiny app is a web page (UI) connected to a Add inputs to the UI with *Input() functions
library(shiny) collect values from the user
computer running a live R session (Server)
Add outputs with *Output() functions
ui <- fluidPage( Access the current value of an input object with
numericInput(inputId = "n",
"Sample size", value = 25), input$<inputId>. Input values are reactive.
Tell server how to render outputs with R in plotOutput(outputId = "hist")
the server function. To do this: ) actionButton(inputId, label, icon,
…)
1. Refer to outputs with output$<id> server <- function(input, output) {
output$hist <- renderPlot({
2. Refer to inputs with input$<id> hist(rnorm(input$n))
actionLink(inputId, label, icon, …)
Users can manipulate the UI, which will cause })
the server to update the UI’s displays (by 3. Wrap code in a render*() function before }

running R code). saving to output shinyApp(ui = ui, server = server) checkboxGroupInput(inputId, label,
Save your template as app.R. Alternatively, split your template into two files named ui.R and server.R. choices, selected, inline)
APP TEMPLATE library(shiny) # ui.R
fluidPage(
ui.R contains everything checkboxInput(inputId, label,
Begin writing a new app with this template. ui <- fluidPage(
numericInput(inputId = "n", you would save to ui. value)
numericInput(inputId = "n",
Preview the app by running the code at the R "Sample size", value = 25), "Sample size", value = 25),
command line. plotOutput(outputId = "hist") plotOutput(outputId = "hist")
) ) server.R ends with the dateInput(inputId, label, value, min,
function you would save max, format, startview, weekstart,
server <- function(input, output) { # server.R
library(shiny) output$hist <- renderPlot({ to server. language)
ui <- fluidPage() hist(rnorm(input$n)) function(input, output) {
}) output$hist <- renderPlot({
server <- function(input, output){} } hist(rnorm(input$n)) No need to call
}) dateRangeInput(inputId, label,
shinyApp(ui = ui, server = server) shinyApp(ui = ui, server = server) } shinyApp(). start, end, min, max, format,
Save each app as a directory that holds an app.R file (or a server.R file and a ui.R file) plus optional extra files. startview, weekstart, language,
• uiHTML
- nested R functions that assemble an
user interface for your app
app-name The directory name is the name of the app
separator)
"
.r app.R (optional) defines objects available to both
Launch apps with fileInput(inputId, label, multiple,
• server - a function with instructions on how
to build and rebuild the R objects displayed
"
"
global.R
DESCRIPTION
ui.R and server.R
(optional) used in showcase mode
runApp(<path to
directory>)
accept)
in the UI " README (optional) data, scripts, etc.
" <other files> (optional) directory of files to share with web numericInput(inputId, label, value,
• shinyApp - combines ui and server into
an app. Wrap with runApp() if calling from a
! www browsers (images, CSS, .js, etc.) Must be named "www" min, max, step)

sourced script or inside a function. passwordInput(inputId, label,


Outputs - render*() and *Output() functions work together to add R output to the UI value)
SHARE YOUR APP works
with
DT::renderDataTable(expr, options, dataTableOutput(outputId, icon, …) radioButtons(inputId, label,
The easiest way to share your app choices, selected, inline)
is to host it on shinyapps.io, a callback, escape, env, quoted)
cloud based service from RStudio renderImage(expr, env, quoted, imageOutput(outputId, width, height,
deleteFile) click, dblclick, hover, hoverDelay, inline, selectInput(inputId, label, choices,
hoverDelayType, brush, clickId, hoverId) selected, multiple, selectize, width,
1. Create a free or professional account at size) (also selectizeInput())
http://shinyapps.io renderPlot(expr, width, height, res, …, plotOutput(outputId, width, height, click,
env, quoted, func) dblclick, hover, hoverDelay, inline, sliderInput(inputId, label, min, max,
2. Click the Publish icon in the RStudio IDE hoverDelayType, brush, clickId, hoverId) value, step, round, format, locale,
or run: ticks, animate, width, sep, pre,
renderPrint(expr, env, quoted, func, verbatimTextOutput(outputId) post)
rsconnect::deployApp("<path to directory>") width)
renderTable(expr,…, env, quoted, func) tableOutput(outputId)
Build or purchase your own Shiny Server submitButton(text, icon)
at www.rstudio.com/products/shiny-server/ renderText(expr, env, quoted, func) textOutput(outputId, container, inline) (Prevents reactions across entire app)
uiOutput(outputId, inline, container, …)
renderUI(expr, env, quoted, func) & textInput(inputId, label, value)
htmlOutput(outputId, inline, container, …)
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at shiny.rstudio.com • shiny 0.12.0 • Updated: 2016-01
Reactivity UI - An app’s UI is an HTML document. Layouts
Reactive values work together with reactive functions. Call a reactive value from within the arguments of one Use Shiny’s functions to assemble this HTML with R. Combine multiple elements
of these functions to avoid the error Operation not allowed without an active reactive context. fluidPage( into a "single element" that
textInput("a","") Returns has its own properties with
) HTML a panel function, e.g.
## <div class="container-fluid">
## <div class="form-group shiny-input-container"> wellPanel(dateInput("a", ""),
## <label for="a"></label> submitButton()
## <input id="a" type="text" )
## class="form-control" value=""/>
absolutePanel() navlistPanel()
## </div>
conditionalPanel() sidebarPanel()
## </div> fixedPanel() tabPanel()
headerPanel() tabsetPanel()
Add static HTML elements with tags, a list of inputPanel() titlePanel()
functions that parallel common HTML tags, e.g. mainPanel() wellPanel()
tags$a(). Unnamed arguments will be passed
into the tag; named arguments will become tag Organize panels and elements into a layout with a
attributes. layout function. Add elements as arguments of the
fluidRow() layout functions.
tags$a tags$data tags$h6 tags$nav tags$span
tags$abbr tags$datalist tags$head tags$noscript tags$strong
tags$address tags$dd tags$header tags$object tags$style ui <- fluidPage(
tags$area tags$del tags$hgroup tags$ol tags$sub row
column col fluidRow(column(width = 4),
tags$article tags$details tags$hr tags$optgroup tags$summary column(width = 2, offset = 3)),
tags$aside tags$dfn tags$HTML tags$option tags$sup column fluidRow(column(width = 12))
tags$audio tags$div tags$i tags$output tags$table )
CREATE YOUR OWN REACTIVE VALUES RENDER REACTIVE OUTPUT tags$b tags$dl tags$iframe tags$p tags$tbody
tags$base tags$dt tags$img tags$param tags$td
# example snippets *Input() functions library(shiny) render*() functions tags$bdi tags$em tags$input tags$pre tags$textarea flowLayout()
(see front page) tags$bdo tags$embed tags$ins tags$progress tags$tfoot ui <- fluidPage(
ui <- fluidPage( (see front page) tags$blockquote tags$eventsource tags$kbd tags$q tags$th object object object flowLayout( # object 1,
ui <- fluidPage( textInput("a","","A"),
1 2 3
textInput("a","","A") reactiveValues(…) )
textOutput("b") tags$body
tags$br
tags$fieldset tags$keygen
tags$figcaption tags$label
tags$ruby
tags$rp
tags$thead
tags$time
# object 2,
) Builds an object to # object 3
tags$button tags$figure tags$legend tags$rt tags$title object 3
server <- display. Will rerun code in )
Each input function tags$canvas tags$footer tags$li tags$s tags$tr
)
server <- creates a reactive value
function(input,output){ body to rebuild the object tags$caption tags$form tags$link tags$samp tags$track
output$b <-
function(input,output){
stored as input$<inputId> renderText({ whenever a reactive value tags$cite tags$h1 tags$mark tags$script tags$u sidebarLayout()
rv <- reactiveValues() tags$code tags$h2 tags$map tags$section tags$ul ui <- fluidPage(
rv$number <- 5 input$a in the code changes.
}) tags$col tags$h3 tags$menu tags$select tags$var sidebarLayout(
} reactiveValues() creates a } Save the results to tags$colgroup tags$h4 tags$meta tags$small tags$video sidebarPanel(),
list of reactive values tags$command tags$h5 tags$meter tags$source tags$wbr side main mainPanel()
shinyApp(ui, server) output$<outputId> panel
whose values you can set. The most common tags have wrapper functions. You panel )
)
do not need to prefix their names with tags$
PREVENT REACTIONS TRIGGER ARBITRARY CODE
ui <- fluidPage( splitLayout()
library(shiny) isolate(expr) library(shiny) observeEvent(eventExpr h1("Header 1"),
hr(),
ui <- fluidPage(
ui <- fluidPage( ui <- fluidPage( , handlerExpr, event.env, splitLayout( # object 1,
textInput("a","","A"), Runs a code block. textInput("a","","A"), event.quoted, handler.env,
br(), object object # object 2
textOutput("b") Returns a non-reactive actionButton("go","Go")
handler.quoted, labe,
p(strong("bold")),
1 2 )
) ) p(em("italic")),
copy of the results. suspended, priority, domain, )
p(code("code")),
server <- server <- autoDestroy, ignoreNULL)
function(input,output){ a(href="", "link"),
function(input,output){
output$b <- observeEvent(input$go,{ HTML("<p>Raw html</p>") verticalLayout() ui <- fluidPage(
renderText({ print(input$a) Runs code in 2nd ) verticalLayout( # object 1,
isolate({input$a}) }) object 1 # object 2,
}) } argument when reactive
} values in 1st argument # object 3
object 2
change. See observe() for To include a CSS file, use includeCSS(), or )
shinyApp(ui, server) shinyApp(ui, server) )
alternative. 1. Place the file in the www subdirectory object 3
2. Link to it with
MODULARIZE REACTIONS DELAY REACTIONS Layer tabPanels on top of each other,
tags$head(tags$link(rel = "stylesheet", and navigate between them, with:
type = "text/css", href = "<file name>"))
ui <- fluidPage(
textInput("a","","A"), reactive(x, env, quoted, library(shiny) eventReactive(eventExpr, ui <- fluidPage( tabsetPanel(
textInput("z","","Z"),
textOutput("b"))
label, domain) ui <- fluidPage(
textInput("a","","A"),
valueExpr, event.env, tabPanel("tab 1", "contents"),
Creates a reactive expression event.quoted, value.env, tabPanel("tab 2", "contents"),
server <-
actionButton("go","Go"),
textOutput("b")
To include JavaScript, use includeScript() or tabPanel("tab 3", "contents")))
function(input,output){ that ) value.quoted, label, 1. Place the file in the www subdirectory
re <- reactive({ • caches its value to reduce server <-
domain, ignoreNULL) 2. Link to it with ui <- fluidPage( navlistPanel(
paste(input$a,input$z)}) computation function(input,output){ tabPanel("tab 1", "contents"),
output$b <- renderText({ re <- eventReactive( Creates reactive
• can be called by other code tags$head(tags$script(src = "<file name>")) tabPanel("tab 2", "contents"),
re() input$go,{input$a})
output$b <- renderText({
expression with code in tabPanel("tab 3", "contents")))
})
} • notifies its dependencies re() 2nd argument that only
shinyApp(ui, server) when it ha been invalidated }) invalidates when reactive IMAGES To include an image ui <- navbarPage(title = "Page",
}
Call the expression with values in 1st argument 1. Place the file in the www subdirectory tabPanel("tab 1", "contents"),
function syntax, e.g. re() shinyApp(ui, server)
change. 2. Link to it with img(src="<file name>") tabPanel("tab 2", "contents"),
tabPanel("tab 3", "contents"))
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at shiny.rstudio.com • shiny 0.12.0 • Updated: 2016-01