You are on page 1of 2

Shiny : : CHEAT SHEET

Basics Building an AppComplete 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 library(shiny) collect values from the user
a computer running a live R session (Server) Add inputs to the UI with *Input() functions
ui <- fluidPage( Access the current value of an input object
Add outputs with *Output() functions numericInput(inputId = "n", with input$<inputId>. Input values are
"Sample size", value = 25), 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))
Users can manipulate the UI, which will }) actionLink(inputId, label, icon, …)
3. Wrap code in a render*() function before }
cause the server to update the UI’s displays saving to output
(by running R code). shinyApp(ui = ui, server = server) checkboxGroupInput(inputId,
Save your template as app.R. Alternatively, split your template into two files named ui.R and server.R. label, choices, selected, inline)
APP TEMPLATE library(shiny) # ui.R
ui <- fluidPage( fluidPage( ui.R contains everything checkboxInput(inputId, label,
Begin writing a new app with this template. numericInput(inputId = "n", you would save to ui. value)
numericInput(inputId = "n",
Preview the app by running the code at the "Sample size", value = 25), "Sample size", value = 25),
R command line. plotOutput(outputId = "hist") plotOutput(outputId = "hist")
) ) server.R ends with the dateInput(inputId, label, value,
function you would save min, max, format, startview,
server <- function(input, output) { to server.
library(shiny) output$hist <- renderPlot({ # server.R weekstart, 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(). start, end, min, max, format,
shinyApp(ui = ui, server = server) }
Save each app as a directory that holds an app.R file (or a server.R file and a ui.R file) plus optional startview, weekstart, language,
extra files. separator)
• uiHTML
- nested R functions that assemble an app-name The directory name is the name of the app
user interface for your app .r app.R (optional) defines objects available to both
ui.R and server.R
fileInput(inputId, label, multiple,
global.R Launch apps with accept)
• server - a function with instructions on how
to build and rebuild the R objects DESCRIPTION (optional) used in showcase mode runApp(<path to
directory>)
README (optional) data, scripts, etc.
displayed in the UI numericInput(inputId, label, value,
<other files> (optional) directory of files to share with web min, max, step)
browsers (images, CSS, .js, etc.) Must be named
• shinyApp - combines ui and server into an
app. Wrap with runApp() if calling from a
www
"www"
passwordInput(inputId, label,
sourced script or inside a function. value)
Outputs - render*() and *Output() functions work together to add R output to the UI
SHARE YOUR APP - in three ways: works dataTableOutput(outputId, icon, …) radioButtons(inputId, label,
with choices, selected, inline)
1. Host it on shinyapps.io, a cloud based
service from RStudio. To do so: DT::renderDataTable(expr, options,
callback, escape, env, quoted) imageOutput(outputId, width, height, selectInput(inputId, label, choices,
Create a free or professional click, dblclick, hover, hoverDelay, inline, selected, multiple, selectize,
account at http://shinyapps.io renderImage(expr, env, quoted, hoverDelayType, brush, clickId,
deleteFile) hoverId) width, size) (also
Click the Publish icon in RStudio IDE, or run: selectizeInput())
rsconnect::deployApp("<path to directory>") plotOutput(outputId, width, height, click,
renderPlot(expr, width, height, res, …, dblclick, hover, hoverDelay, inline, sliderInput(inputId, label, min,
2. Purchase RStudio Connect, a env, quoted, func) hoverDelayType, brush, clickId, max, value, step, round, format,
publishing platform for R and Python.
hoverId) locale, ticks, animate, width, sep,
www.rstudio.com/products/connect/ verbatimTextOutput(outputId) pre, post)
renderPrint(expr, env, quoted, func,
width)
3. Build your own Shiny Server submitButton(text, icon)
renderTable(expr,…, env, quoted, func) tableOutput(outputId)
https://rstudio.com/products/shiny/shiny-server/ (Prevents reactions across entire
renderText(expr, env, quoted, func) textOutput(outputId, container, inline) app)
uiOutput(outputId, inline, container, …)
renderUI(expr, env, quoted, func) & htmlOutput(outputId, inline, container, …) textInput(inputId, label, value)
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.
Use Shiny’s functions to assemble this HTML with
Layouts
Reactive values work together with reactive functions. Call a reactive value from within the arguments Combine multiple
R.
of one of these functions to avoid the error Operation not allowed without an active reactive context. elements into a "single
fluidPage( element" that has its own
textInput("a","") Returns
HTML properties with 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 inputPanel() titlePanel()
of functions that parallel common HTML mainPanel() wellPanel()
tags, e.g. tags$a(). Unnamed arguments
will be passed into the tag; named Organize panels and elements into a layout with a
arguments will become tag attributes. layout function. Add elements as arguments of the
layout functions.
tags$a tags$data tags$h6 tags$nav tags$span fluidRow()
tags$abbr tags$datalist tags$head tags$noscript tags$strong ui <- fluidPage(
tags$address tags$dd tags$headertags$object tags$style fluidRow(column(width = 4),
tags$area tags$del tags$hgrouptags$ol tags$sub
row
column col
column(width = 2, offset =
tags$article tags$details tags$hr tags$optgroup tags$summary
tags$aside tags$dfn tags$HTML tags$option tags$sup
3)),
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) ui <- fluidPage( (see front page) tags$bdo tags$embed tags$ins tags$progresstags$tfoot ui <- fluidPage(
tags$blockquot tags$eventsourc tags$kbd tags$q tags$th object object object flowLayout( # object 1,
ui <- fluidPage( textInput("a","","A"),
textInput("a","","A")
reactiveValues(…) textOutput("b") e e tags$keygentags$ruby tags$thead 1 2 3
# object 2,
) ) Builds an object to tags$body tags$fieldset tags$label tags$rp tags$time # object 3
object
Each input function display. Will rerun code tags$br tags$figcaption tags$legend tags$rt tags$title
3 )
server <- function(input,output) tags$li
creates a reactive value {
in body to rebuild the tags$button tags$figure tags$s tags$tr )
server <- function(input,output){ tags$canvas tags$footer tags$link tags$samp tags$track
rv <- reactiveValues() stored as output$b <- object whenever a
rv$number <- 5 input$<inputId> renderText({ reactive value in the tags$caption tags$form tags$mark tags$script tags$u sidebarLayout() ui <- fluidPage(
input$a tags$cite tags$h1 tags$map tags$section tags$ul
}
})
code changes. tags$code tags$h2 tags$menu tags$select tags$var sidebarLayout(
reactiveValues() creates } tags$col tags$h3 tags$meta tags$small tags$video sidebarPanel(),
a list of reactive values Save the results to tags$colgroup tags$h4 tags$meter tags$source tags$wbr side main mainPanel()
whose values you can shinyApp(ui, server) output$<outputId> panel panel )
set. The most common tags have wrapper functions. )
You do not need to prefix their names with tags$
PREVENT REACTIONS TRIGGER ARBITRARY CODE
ui <- fluidPage( splitLayout()
library(shiny) isolate(expr) library(shiny) observeEvent(eventExp h1("Header 1"),
ui <- fluidPage(
r, handlerExpr, hr(),
ui <- fluidPage( ui <- fluidPage( splitLayout( # object 1,
textInput("a","","A"), Runs a code block. textInput("a","","A"), event.env, event.quoted, br(), object object # object 2
textOutput("b") Returns a non-reactive actionButton("go","Go") handler.env, p(strong("bold")), 1 2 )
) handler.quoted, labe,
) copy of the results. p(em("italic")),
)
suspended, priority, p(code("code")),
server <- function(input,output) server <- function(input,output){ domain, autoDestroy,
{ observeEvent(input$go,{ a(href="", "link"), ui <- fluidPage(
output$b <- print(input$a) ignoreNULL) HTML("<p>Raw html</p>") verticalLayout() verticalLayout( # object 1,
renderText({ }) Runs code in 2nd ) # object
} object
isolate({input$a})
argument when reactive 2,
}) # object
} values in 1st argument object
shinyApp(ui, server) To include a CSS file, use includeCSS(), 3
change. See observe() or
shinyApp(ui, server) for alternative. object )
1. Place the file in the www subdirectory )
2. Link to it with Layer tabPanels on top of each
MODULARIZE REACTIONS DELAY REACTIONS tags$head(tags$link(rel = "stylesheet", other, and navigate between them,
type = "text/css", href = "<file name>")) with:
ui <- fluidPage( reactive(x, env, quoted, library(shiny) eventReactive(eventExpr, ui <- fluidPage( tabsetPanel(
textInput("a","","A"),
label, domain) valueExpr, event.env, tabPanel("tab 1", "contents"),
textInput("z","","Z"), ui <- fluidPage(
tabPanel("tab 2", "contents"),
textOutput("b")) textInput("a","","A"), event.quoted, value.env, To include JavaScript, use includeScript() tabPanel("tab 3",
Creates a reactive actionButton("go","Go"),
value.quoted, label, or
server <- function(input,output){ expression that textOutput("b") "contents")))
ui <- fluidPage( navlistPanel(
re <- reactive({
• caches its value to reduce
) domain, ignoreNULL) 1. Place the file in the www subdirectory tabPanel("tab 1",
paste(input$a,input$z)})
output$b <- renderText({ computation server <- function(input,output){ 2. Link to it with "contents"),
Creates reactive tabPanel("tab 2",
re() • can be called by other code reinput$go,{input$a})
<- eventReactive(
tags$head(tags$script(src = "<file name>")) "contents"),
}) expression with code in ui <- navbarPage(title
} • notifies its dependencies output$b <- renderText({
2nd argument that only tabPanel("tab 3", =
shinyApp(ui, server) when it ha been invalidated re() "Page",
"contents")))
}) invalidates when IMAGES To include an image tabPanel("tab 1",
Call the expression with } reactive values in 1st "contents"),
function syntax, e.g. re() 1. Place the file in the www subdirectory
argument change. tabPanel("tab 2",
2. Link to it with img(src="<file name>")
"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

You might also like