Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Shiny : : CHEATSHEET

Building an App To generate the template, type shinyapp and press Tab in the RStudio IDE
or go to File > New Project > New Directory > Shiny Application
Inputs
Collect values from the user.
A Shiny app is a web page (ui)
# app.R
connected to a computer library(shiny) Access the current value of an input object with
running a live R session (server). Customize the UI with Layout Functions input$<inputId>. Input values are reactive.
In ui nest R ui <- fluidPage(
functions to numericInput(inputId = "n", Add Inputs with *Input() functions actionButton(inputId, label, icon,
build an HTML "Sample size", value = 25), width, …)
interface plotOutput(outputId = "hist") Add Outputs with *Output() functions
)
actionLink(inputId, label, icon, …)
Users can manipulate the UI,
which will cause the server to server <- function(input, output, session) { checkboxGroupInput(inputId,
update the UI’s displays (by Tell the server output$hist <- renderPlot({ label, choices, selected, inline, width,
how to render Wrap code in render*() functions
running R code). hist(rnorm(input$n)) choiceNames, choiceValues)
outputs and before saving to output
})
respond to } Refer to UI inputs with input$<id> checkboxInput(inputId, label, value,
Save your template as app.R. inputs with R and outputs with output$<id> width)
Keep your app in a directory
along with optional extra files. shinyApp(ui = ui, server = server) dateInput(inputId, label, value, min,
max, format, startview, weekstart,
app-name Call shinyApp() to combine ui and server into an interactive app!
language, width, autoclose,
The directory name is the app name datesdisabled, daysofweekdisabled)
app.R (optional) used in showcase mode
DESCRIPTION
(optional) directory of supplemental .R files that are sourced dateRangeInput(inputId, label, start,
README automatically, must be named "R" See annotated examples of Shiny apps by running end, min, max, format, startview,
R/ runExample(<example name>). Run runExample() weekstart, language, separator, width,
(optional) directory of files to share with web browsers (images, autoclose)
www/ CSS, .js, etc.), must be named "www" with no arguments for a list of example names.
Launch apps stored in a directory with runApp(<path to directory>). fileInput(inputId, label, multiple,
accept, width, buttonLabel, placeholder)

Share Outputs render*() and *Output() functions work together to add R output to the UI. numericInput(inputId, label, value,
min, max, step, width)
Share your app in three ways: DT::renderDataTable(expr, options, dataTableOutput(outputId)
searchDelay, callback, escape, env, quoted, passwordInput(inputId, label, value,
1. Host it on shinyapps.io, a cloud based outputArgs) width, placeholder)
service from Posit. To deploy Shiny apps:
renderImage(expr, env, quoted, deleteFile, imageOutput(outputId, width, height, radioButtons(inputId, label,
Create a free or professional outputArgs) click, dblclick, hover, brush, inline) choices, selected, inline, width,
account at shinyapps.io choiceNames, choiceValues)
renderPlot(expr, width, height, res, …, alt, env, plotOutput(outputId, width, height, click,
Click the Publish icon in RStudio IDE, or run: quoted, execOnResize, outputArgs) dblclick, hover, brush, inline) selectInput(inputId, label, choices,
rsconnect::deployApp("<path to directory>") selected, multiple, selectize, width, size)
Also selectizeInput()
renderPrint(expr, env, quoted, width, verbatimTextOutput(outputId,
2. Purchase Posit Connect, a outputArgs) placeholder)
publishing platform for R and Python. sliderInput(inputId, label, min, max,
value, step, round, format, locale, ticks,
posit.co/products/enterprise/connect/ renderTable(expr, striped, hover, bordered, tableOutput(outputId) animate, width, sep, pre, post,
spacing, width, align, rownames, colnames, timeFormat, timezone, dragRange)
digits, na, …, env, quoted, outputArgs)
3. Build your own Shiny Server
posit.co/products/open-source/shinyserver/ renderText(expr, env, quoted, outputArgs, sep) textOutput(outputId, container, inline) textInput(inputId, label, value, width,
placeholder) Also textAreaInput()
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.
CC BY SA Posit So ware, PBC • info@posit.co • posit.co • Learn more at shiny.posit.co • HTML cheatsheets at pos.it/cheatsheets • shiny 1.7.4 • Updated: 2023-07
ft
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 a
) HTML panel function, e.g.
## <div class="container-fluid"> wellPanel(
## <div class="form-group shiny-input-container"> dateInput("a", ""),
## <label for="a"></label> submitButton()
## <input id="a" type="text" )
## class="form-control" value=""/>
## </div> absolutePanel() navlistPanel()
## </div> conditionalPanel() sidebarPanel()
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.
Run names(tags) for a complete list. sidebarLayout()
tags$h1("Header") -> <h1>Header</h1> ui <- fluidPage(
sidebarLayout(
The most common tags have wrapper functions. You side main sidebarPanel(),
CREATE YOUR OWN REACTIVE VALUES RENDER REACTIVE OUTPUT do not need to prefix their names with tags$ panel
panel mainPanel()
)
# *Input() example *Input() functions ui <- fluidPage( render*() functions ui <- fluidPage( )
textInput("a","","A"), h1("Header 1"),
ui <- fluidPage( Each input function creates textOutput("b") Builds an object to hr(), fluidRow()
textInput("a","","A") a reactive value stored as )
display. Will rerun code in br(),
)
input$<inputId>. ui <- fluidPage(
server <- body to rebuild the object p(strong("bold")), row
column col fluidRow(column(width = 4),
function(input,output){ whenever a reactive value p(em("italic")), column(width = 2, o set = 3)),
#reactiveVal example
reactiveVal(…) output$b <-
renderText({ in the code changes. p(code("code")),
column fluidRow(column(width = 12))
server <- a(href="", "link"),
function(input,output){ Creates a single reactive input$a
HTML("<p>Raw html</p>")
)
rv <- reactiveVal() values object. }) Save the results to )
rv$number <- 5 }
output$<outputId>. Also flowLayout(), splitLayout(), verticalLayout(),
} reactiveValues(…) shinyApp(ui, server) fixedPage(), and fixedRow().
Creates a list of names
reactive values. PERFORM SIDE EFFECTS To include a CSS file, use includeCSS(), or
1. Place the file in the www subdirectory Layer tabPanels on top of each other,
observe(x, env) and navigate between them, with:
CREATE REACTIVE EXPRESSIONS ui <- fluidPage( 2. Link to it with:
textInput("a","","A"), Creates an observer from ui <- fluidPage( tabsetPanel(
ui <- fluidPage(
textInput("a","","A"),
reactive(x, env, quoted, )
actionButton("go","Go")
the given expression. tags$head(tags$link(rel = "stylesheet", tabPanel("tab 1", "contents"),
textInput("z","","Z"), label, domain) type = "text/css", href = "<file name>")) tabPanel("tab 2", "contents"),
textOutput("b")) server <- observeEvent(eventExpr, tabPanel("tab 3", "contents")))
Reactive expressions: function(input,output){ handlerExpr, event.env,
server <-
function(input,output){ • cache their value to observeEvent(
event.quoted, handler.env,
To include JavaScript, use includeScript() or
re <- reactive({ input$go,{ 1. Place the file in the www subdirectory ui <- fluidPage( navlistPanel(
paste(input$a,input$z) reduce computation print(input$a) handler.quoted, ..., label, tabPanel("tab 1", "contents"),
}) • can be called elsewhere } suspended, priority, domain, 2. Link to it with: tabPanel("tab 2", "contents"),
output$b <- renderText({ ) autoDestroy, ignoreNULL,
re() • notify dependencies } tabPanel("tab 3", "contents")))
}) ignoreInit, once) tags$head(tags$script(src = "<file name>"))
} when invalidated
shinyApp(ui, server) ui <- navbarPage(title = "Page",
shinyApp(ui, server) Call the expression with Runs code in 2nd IMAGES To include an image:
tabPanel("tab 1", "contents"),
function syntax, e.g. re(). argument when reactive 1. Place the file in the www subdirectory tabPanel("tab 2", "contents"),
values in 1st argument 2. Link to it with img(src="<file name>") tabPanel("tab 3", "contents"))
REACT BASED ON EVENT change.
eventReactive(eventExpr,
Themes
ui <- fluidPage(
textInput("a","","A"),
actionButton("go","Go"), valueExpr, event.env, REMOVE REACTIVITY
textOutput("b") event.quoted, value.env, ui <- fluidPage( isolate(expr)
)
value.quoted, ..., label, textInput("a","","A"), Use the bslib package to add existing themes to Build your own theme by customizing individual
server <- domain, ignoreNULL, )
textOutput("b") Runs a code block. your Shiny app ui, or make your own. arguments.
function(input,output){
re <- eventReactive( ignoreInit) Returns a non-reactive bs_theme(bg = "#558AC5",
input$go,{input$a} server <- copy of the results. library(bslib)
) Creates reactive function(input,output){ fg = "#F9B02D",
output$b <- renderText({ ui <- fluidPage(
re() expression with code in output$b <-
theme = bs_theme( ...)
renderText({
}) 2nd argument that only isolate({input$a}) bootswatch = "darkly",
}
invalidates when reactive }) ... ?bs_theme for a full list
shinyApp(ui, server) values in 1st argument }
) of arguments.
change. shinyApp(ui, server) )
bs_themer() Place within the server function to
bootswatch_themes() Get a list of themes. use the interactive theming widget.
CC BY SA Posit So ware, PBC • info@posit.co • posit.co • Learn more at shiny.posit.co • HTML cheatsheets at pos.it/cheatsheets • shiny 1.7.4 • Updated: 2023-07
ft
ff

You might also like