Shiny
Shiny
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 • [email protected] • posit.co • Learn more at shiny.posit.co • HTML cheatsheets at pos.it/cheatsheets • shiny 1.8.1.1 • Updated: 2024-05
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.
Use the bslib package to
of these functions to avoid the error Operation not allowed without an active reactive context. fluidPage( lay out the your app and
textInput("a","") Returns
) HTML its components.
## <div class="container-fluid">
## <div class="form-group shiny-input-container">
PAGE LAYOUTS
## <label for="a"></label> Dashboard layouts
## <input id="a" type="text"
## class="form-control" value=""/> page_sidebar() A sidebar page
## </div>
## </div>
page_navbar() Multi-page app with a top navigation bar
page_fillable() A screen-filling page layout
Add static HTML elements with tags, a list
Basic layouts
of functions that parallel common HTML
tags, e.g. tags$a(). Unnamed arguments page() page_fluid() page_fixed()
will be passed into the tag; named
arguments will become tag attributes. USER INTERFACE LAYOUTS
Run names(tags) for a complete list. Multiple columns
tags$h1("Header") -> <h1>Header</h1>
layout_columns() Organize UI elements into
The most common tags have wrapper functions. You Bootstrap’s 12-column CSS grid
CREATE YOUR OWN REACTIVE VALUES RENDER REACTIVE OUTPUT do not need to prefix their names with tags$
layout_column_wrap() Organize elements into a grid
# *Input() example *Input() functions ui <- fluidPage( render*() functions ui <- fluidPage( of equal-width columns
textInput("a","","A"), h1("Header 1"),
ui <- fluidPage( Each input function creates Builds an object to
textInput("a","","A") a reactive value stored as )
textOutput("b") hr(), Multiple panels
) display. Will rerun code in br(),
input$<inputId>. body to rebuild the object p(strong("bold")),
server <-
function(input,output){ whenever a reactive value p(em("italic")), navset_tab()
#reactiveVal example
reactiveVal(…) output$b <-
renderText({ in the code changes. p(code("code")),
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>. navset_pill()
} reactiveValues(…) shinyApp(ui, server)
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 navset_underline()
CREATE REACTIVE EXPRESSIONS ui <- fluidPage( observe(x, env) 2. Link to it with:
textInput("a","","A"), Creates an observer from
ui <- fluidPage( reactive(x, env, quoted, actionButton("go","Go")
the given expression. tags$head(tags$link(rel = "stylesheet",
textInput("a","","A"), ) nav_panel() Content to display when given item is selected
textInput("z","","Z"), label, domain) type = "text/css", href = "<file name>"))
textOutput("b")) server <- observeEvent(eventExpr, nav_menu() Create a menu of nav items
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 nav_item() Place arbitrary content in the nav panel
re <- reactive({
reduce computation
input$go,{
handler.quoted, ..., label, 1. Place the file in the www subdirectory
paste(input$a,input$z) print(input$a) nav_spacer() Add spacing between nav items
}) • can be called elsewhere } suspended, priority, domain, 2. Link to it with:
output$b <- renderText({ )
re() • notify dependencies }
autoDestroy, ignoreNULL, Also dynamically update nav containers with nav_select(),
}) ignoreInit, once) tags$head(tags$script(src = "<file name>"))
} when invalidated nav_insert(), nav_remove(), nav_show(), nav_hide().
shinyApp(ui, server)
shinyApp(ui, server) Call the expression with Runs code in 2nd IMAGES To include an image:
function syntax, e.g. re(). argument when reactive 1. Place the file in the www subdirectory Sidebar layout
values in 1st argument 2. Link to it with img(src="<file name>")
REACT BASED ON EVENT change. sidebar() layout_sidebar() toggle_sidebar()
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 • [email protected] • posit.co • Learn more at shiny.posit.co • HTML cheatsheets at pos.it/cheatsheets • shiny 1.8.1.1 • Updated: 2024-05
ft