Translations (PDF)
- French
- German
- Spanish
- Turkish
- Vietnamese
Building an App
A Shiny app is a web page (ui
) connected to a computer running a live R session (server
).
library(shiny)
Users can manipulate the UI, which will cause the server to update the UI’s display (by running R code).
Save your template as app.R
. Keep your app in a directory along with optional extra files.
- app-name: The directory name is the app name
- app.R
- DESCRIPTION and README: (optional) used in showcase mode
- R/: (optional) directory of supplemental .R files that are sourced automatically, must be named
R
- www/: (optional) directory of files to share with web browsers (images, CSS, .js, etc.), must be named
www
Launch apps stored in a directory with runApp(<path to directory>)
.
To generate the template, type shinyApp
and press Tab
in the RStudio IDE or go to File > New Project > New Directory > Shiny Application.
# app.R library(shiny)#In ui nest R functions to build an HTML interfaceui <- fluidPage( numericInput(inputId = "n", "Sample size", value = 25), plotOutput(outputId = "hist"))# Customize the UI with Layout Functions# Add Inputs with *Input() functions# Add Outputs with *Output() functions# Tell the server how to render outputs and respond to inputs with Rserver <- function(input, output, session) { output$hist <- renderPlot({ hist(rnorm(input$n)) })}# Wrap code in render*() functions before saving to output# Refer to UI inputs with input$<id> and outputs with output$<id> # Call shinyApp() to combine ui and server into an interactive app!shinyApp(ui = ui, server = server)
See annotated examples of Shiny apps by running runExample(<example name>)
. Run runExample()
with no arguments for a list of example names.
Outputs
render*()
and *Output()
functions work together to add R output to the UI.
render*() Functions | *Output() Functions |
---|---|
DT::renderDataTable(expr, options, searchDelay, callback, escape, env, quoted, outputArgs) | dataTableOutput(outputId) |
renderImage(expr, env, quoted, deleteFile, outputArgs) | imageOutput(outputId, width, height, click, dblclick, hover, brush, inline) |
renderPlot(expr, width, height, res, …, alt, env, quoted, execOnResixe, outputArgs | plotOutput(outputId, width, height, click, dblclick, hover, brush, inline) |
renderPrint(expr, env, quoted, width, outputArgs) | verbatimTextOutput(outputId, placeholder) |
renderTable(expr, striped, hover, bordered, spacing, width, align, rownames, colnames, digits, na, …, env, quoted, outputArgs) | tableOutput(outputId) |
renderText(expr, env, quoted, outputArgs, sep) | textOutput(outputId, container, inline) |
renderUI(expr, env, quoted, outputArgs) | uiOutput(outputId, inline, container, …) htmlOutput(outputId, inline, container, …) |
These are the core output types. See htmlwidgets.org for many more options.
Inputs
Collect values from the user.
Access the current value of an input object with input$<inputId>
. Input values are reactive.
actionButton(inputId, label, icon, width, ...)
actionLink(inputId, label, icon, ...)
checkboxGroupInput(inputId, label, choices, selected, inline, width, choiceNames, choiceValues)
checkboxInput(inputId, label, value, width)
dateInput(inputId, label, value, min, max, format, startview, weekstart, language, width, autoclose, datesdisabled, daysofweekdisabled)
dateRangeInput(inputId, label, start, end, min, max, format, startview, weekstart, language, separator, width, autoclose)
fileInput(inputId, label, multiple, accept, width, buttonLabel, placeholder)
numericInput(inputId, label, value, min, max, step, width)
passwordInput(inputId, label, value, width, placeholder)
radioButtons(inputId, label, choices, selected, inline, width, choiceNames, choiceValues)
selectInput(inputId, label, choices, selected, multiple, selectize, width, size)
: AlsoselectizeInput()
sliderInput(inputId, label, min, max, value, step, round, format, locale, ticks, animate, width, sep, pre, post, timeFormat, timezone, dragRange)
textInput(inputId, label, value, width, placeholder)
: AlsotextAreaInput()
See AlsoShiny - Getting Started
Reactivity
Reactive values work together with reactive functions. Call a reactive value from within the arguments of one of these functions to avoid the error Operation not allowed without an active reactive context
.
Expand to read about the reactivity diagram
Phases in the reactivity diagram
- Create your own reactive values
reactiveValues()
reactiveFileReader()
reactivePoll()
*Input()
- Perform side effects
observeEvent()
observe()
- Schedule updates
invalidateLater()
- Create reactive expressions
reactive()
- Remove reactivity
isolate()
- React based on event
eventReactive()
- Render reactive output
render*()
Create Your own Reactive Values
*Input()
functions: Each input function creates a reactive value stored asinput$<inputId>
.# *Input() exampleui <- fluidPage( textInput("a","","A"))
reactiveVal():
Creates a single reactive values object.reactiveValues(...)
: Creates a list of reactive values whose values you can set.# reactiveVal exampleserver <- function(input,output){ rv <- reactiveValues() rv$number <- 5}
Create Reactive Expressions
reactive(x, env, quoted, label, domain)
:Reactive expressions:
cache their value to reduce computation
can be called elsewhere
notify dependencies when invalidated
Call the expression with function syntax, e.g.
re()
.library(shiny)ui <- fluidPage( textInput("a","","A"), textInput("z","","Z"), textOutput("b") )server <- function(input,output){ re <- reactive({ paste(input$a,input$z) }) output$b <- renderText({ re() }) }shinyApp(ui, server)
React Based on Event
eventReactive(eventExpr, valueExpr, event.env, event.quoted, value.env, value.quoted, ..., label, domain, ignoreNULL, ignoreInit)
: Creates reactive expression with code in 2nd argument that only invalidates when reactive values in 1st argument change.library(shiny)ui <- fluidPage( textInput("a","","A"), actionButton("go","Go"), textOutput("b"))server <- function(input,output){ re <- eventReactive( input$go,{input$a} ) output$b <- renderText({ re() }) }
Render Reactive Output
render*()
functions: (see front page) Builds an object to display. Will rerun code in body to rebuild the object whenever a reactive value in the code changes. Save the results tooutput$<outputId>
.library(shiny)ui <- fluidPage( textInput("a","","A"), textOutput("b"))server <- function(input,output){ output$b <- renderText({ input$a })}shinyApp(ui, server)
Perform Side Effects
observe(x, env)
: Creates an observer from the given expression.observeEvent(eventExpr, handlerExpr, event.env, event.quoted, handler.env, handler.quoted, ..., label, suspended, priority, domain, autoDestroy, ignoreNULL, ignoreInit, once)
: Runs code in 2nd argument when reactive values in 1st argument change. Alternative toobserve``()
.library(shiny)ui <- fluidPage(textInput("a","","A"), actionButton("go","Go"))server <- function(input,output){ observeEvent(input$go, { print(input$a) })}shinyApp(ui, server)
Remove Reactivity
isolate(expr)
: Runs a code block. Returns a non-reactive copy of the results.library(shiny)ui <- fluidPage( textInput("a","","A"), textOutput("b"))server <- function(input,output){ output$b <- renderText({ isolate({input$a}) })}shinyApp(ui, server)
UI
An app’s UI is an HTML document.
Use Shiny’s functions to assemble this HTML with R.
fluidPage( textInput("a",""))
Returns HTML:
<div class="container-fluid"> <div class="form-group shiny-input-container"> <label for="a"></label> <input id="a" type="text" class="form-control" value=""/> </div></div>
Add static HTML elements with tags, a list of functions that parallel common HTML tags, e.g.tags$a()
. Unnamed arguments will be passed into the tag; named arguments will become tag attributes.
Run names(tags)
for a complete list. tags$h1("Header")
-> <h1>Header</h1>
The most common tags have wrapper functions. You do not need to prefix their names with tags$
.
ui <- fluidPage( h1("Header 1"), # <h1>Header 1</h1> hr(), # <hr> br(), # <br> p(strong("bold")), # <p><strong>bold</strong></p> p(em("italic")), # <p><em>italic</em></p> p(code("code")), # <p><code>code</code></p> a(href="", "link"), # <a href="">link</a> HTML("<p>Raw html</p>") # display raw html)
To include a CSS file, use includeCSS()
, or
Place the file in the
www
subdirectoryLink to it with:
tags$head( tags$link( rel = "stylesheet", type = "text/css", href = "<file name>" ) )
To include JavaScript, use includeScript()
, or
Place the file in the
www
subdirectoryLink to it with:
tags$head(tags$script(src = "<file name>"))
To include an image:
Place the file in the
www
subdirectoryLink to it with:
img(src = "<file name>")
Layouts
Use the bslib package to lay out the your app and its components.
Page layouts
Dashboard layouts
page_sidebar()
- A sidebar pagepage_navbar()
- Multi-page app with a top navigation barpage_fillable()
- A screen-filling page layout
Basic layouts
page()
page_fluid()
page_fixed()
User interface layouts
Multiple columns
layout_columns()
- Organize UI elements into Bootstrap’s 12-column CSS gridlayout_column_wrap()
- Organize elements into a grid of equal-width columns
Multiple panels
navset_tab()
- Tabbed navigation containernavset_pill()
- Creates a navigation container that behaves exactly likenavset_tab()
, but the tab toggles are pills or button-shapednavset_underline()
- Creates a navigation container that behaves exactly likenavset_tab()
andnavset_pill()
, but the active/focused navigation links are styled with an underlinenav_panel()
- Content to display when given item is selectednav_menu()
- Create a menu of nav itemsnav_item()
- Place arbitrary content in the nav panelnav_spacer()
- Add spacing between nav items
Also dynamically update nav containers with nav_select()
, nav_insert()
, nav_remove()
, nav_show()
, nav_hide()
.
Sidebar layout
sidebar()
layout_sidebar()
toggle_sidebar()
Themes
Use the bslib package to add existing themes to your Shiny app ui, or make your own.
library(bslib)ui <- fluidPage( theme = bs_theme( boothswatch = "darkly", ... ))
bootswatch_themes()
: Get a list of themes.
Build your own theme by customizing individual arguments.
bs_theme( bg = "#558AC5", fg = "#F9B02D", ...)
?bs_theme
for a full list of arguments.bs_themer()
: Place within the server function ot use the interactive theming widget.
CC BY SA Posit Software, PBC • info@posit.co • posit.co
Learn more at shiny.rstudio.com
Updated: 2024-05.
packageVersion("shiny")
[1] '1.8.1.1'