Movatterモバイル変換


[0]ホーム

URL:


Type:Package
Title:Web Application Framework for R
Version:1.12.1
Description:Makes it incredibly easy to build interactive web applications with R. Automatic "reactive" binding between inputs and outputs and extensive prebuilt widgets make it possible to build beautiful, responsive, and powerful applications with minimal effort.
License:GPL-3 | file LICENSE
URL:https://shiny.posit.co/,https://github.com/rstudio/shiny
BugReports:https://github.com/rstudio/shiny/issues
Depends:methods, R (≥ 3.0.2)
Imports:bslib (≥ 0.6.0), cachem (≥ 1.1.0), cli, commonmark (≥2.0.0), fastmap (≥ 1.1.1), fontawesome (≥ 0.4.0), glue (≥1.3.2), grDevices, htmltools (≥ 0.5.4), httpuv (≥ 1.5.2),jsonlite (≥ 0.9.16), later (≥ 1.0.0), lifecycle (≥ 0.2.0),mime (≥ 0.3), otel, promises (≥ 1.5.0), R6 (≥ 2.0), rlang(≥ 0.4.10), sourcetools, tools, utils, withr, xtable
Suggests:Cairo (≥ 1.5-5), coro (≥ 1.1.0), datasets, DT, dygraphs,future, ggplot2, knitr (≥ 1.6), magrittr, markdown, mirai,otelsdk (≥ 0.2.0), ragg, reactlog (≥ 1.0.0), rmarkdown, sass,showtext, testthat (≥ 3.2.1), watcher, yaml
Config/Needs/check:shinytest2
Config/testthat/edition:3
Encoding:UTF-8
RoxygenNote:7.3.3
Collate:'globals.R' 'app-state.R' 'app_template.R' 'bind-cache.R''bind-event.R' 'bookmark-state-local.R' 'bookmark-state.R''bootstrap-deprecated.R' 'bootstrap-layout.R' 'conditions.R''map.R' 'utils.R' 'bootstrap.R' 'busy-indicators-spinners.R''busy-indicators.R' 'cache-utils.R' 'deprecated.R' 'devmode.R''diagnose.R' 'extended-task.R' 'fileupload.R' 'graph.R''reactives.R' 'reactive-domains.R' 'history.R' 'hooks.R''html-deps.R' 'image-interact-opts.R' 'image-interact.R''imageutils.R' 'input-action.R' 'input-checkbox.R''input-checkboxgroup.R' 'input-date.R' 'input-daterange.R''input-file.R' 'input-numeric.R' 'input-password.R''input-radiobuttons.R' 'input-select.R' 'input-slider.R''input-submit.R' 'input-text.R' 'input-textarea.R''input-utils.R' 'insert-tab.R' 'insert-ui.R' 'jqueryui.R''knitr.R' 'middleware-shiny.R' 'middleware.R' 'timer.R''shiny.R' 'mock-session.R' 'modal.R' 'modules.R''notifications.R' 'otel-attr-srcref.R' 'otel-collect.R''otel-enable.R' 'otel-error.R' 'otel-label.R''otel-reactive-update.R' 'otel-session.R' 'otel-shiny.R''otel-with.R' 'priorityqueue.R' 'progress.R' 'react.R''reexports.R' 'render-cached-plot.R' 'render-plot.R''render-table.R' 'run-url.R' 'runapp.R' 'serializers.R''server-input-handlers.R' 'server-resource-paths.R' 'server.R''shiny-options.R' 'shiny-package.R' 'shinyapp.R' 'shinyui.R''shinywrappers.R' 'showcase.R' 'snapshot.R' 'staticimports.R''tar.R' 'test-export.R' 'test-server.R' 'test.R''update-input.R' 'utils-lang.R' 'utils-tags.R''version_bs_date_picker.R' 'version_ion_range_slider.R''version_jquery.R' 'version_jqueryui.R' 'version_selectize.R''version_strftime.R' 'viewer.R'
NeedsCompilation:no
Packaged:2025-12-08 21:22:26 UTC; barret
Author:Winston ChangORCID iD [aut], Joe Cheng [aut], JJ Allaire [aut], Carson SievertORCID iD [aut, cre], Barret SchloerkeORCID iD [aut], Garrick Aden-BuieORCID iD [aut], Yihui Xie [aut], Jeff Allen [aut], Jonathan McPherson [aut], Alan Dipert [aut], Barbara Borges [aut], Posit Software, PBCROR ID [cph, fnd], jQuery Foundation [cph] (jQuery library and jQuery UI library), jQuery contributors [ctb, cph] (jQuery library; authors listed in inst/www/shared/jquery-AUTHORS.txt), jQuery UI contributors [ctb, cph] (jQuery UI library; authors listed in inst/www/shared/jqueryui/AUTHORS.txt), Mark Otto [ctb] (Bootstrap library), Jacob Thornton [ctb] (Bootstrap library), Bootstrap contributors [ctb] (Bootstrap library), Twitter, Inc [cph] (Bootstrap library), Prem Nawaz Khan [ctb] (Bootstrap accessibility plugin), Victor Tsaran [ctb] (Bootstrap accessibility plugin), Dennis Lembree [ctb] (Bootstrap accessibility plugin), Srinivasu Chakravarthula [ctb] (Bootstrap accessibility plugin), Cathy O'Connor [ctb] (Bootstrap accessibility plugin), PayPal, Inc [cph] (Bootstrap accessibility plugin), Stefan Petre [ctb, cph] (Bootstrap-datepicker library), Andrew Rowls [ctb, cph] (Bootstrap-datepicker library), Brian Reavis [ctb, cph] (selectize.js library), Salmen Bejaoui [ctb, cph] (selectize-plugin-a11y library), Denis Ineshin [ctb, cph] (ion.rangeSlider library), Sami Samhuri [ctb, cph] (Javascript strftime library), SpryMedia Limited [ctb, cph] (DataTables library), Ivan Sagalaev [ctb, cph] (highlight.js library), R Core Team [ctb, cph] (tar implementation from R)
Maintainer:Carson Sievert <carson@posit.co>
Repository:CRAN
Date/Publication:2025-12-09 09:30:02 UTC

Web Application Framework for R

Description

Shiny makes it incredibly easy to build interactive web applications with R.Automatic "reactive" binding between inputs and outputs and extensiveprebuilt widgets make it possible to build beautiful, responsive, andpowerful applications with minimal effort.

Details

The Shiny tutorial athttps://shiny.rstudio.com/tutorial/ explainsthe framework in depth, walks you through building a simple application, andincludes extensive annotated examples.

Author(s)

Maintainer: Carson Sievertcarson@posit.co (ORCID)

Authors:

Other contributors:

See Also

shiny-options for documentation about global options.


Task or computation that proceeds in the background

Description

In normal Shiny reactive code, whenever an observer, calc, oroutput is busy computing, it blocks the current session from receiving anyinputs or attempting to proceed with any other computation related to thatsession.

TheExtendedTask class allows you to have an expensive operation that isstarted by a reactive effect, and whose (eventual) results can be accessedby a regular observer, calc, or output; but during the course of theoperation, the current session is completely unblocked, allowing the userto continue using the rest of the app while the operation proceeds in thebackground.

Note that eachExtendedTask object does not represent asingleinvocation of its long-running function. Rather, it's an object that isused to invoke the function with different arguments, keeps track ofwhether an invocation is in progress, and provides ways to get at thecurrent status or results of the operation. A singleExtendedTask objectdoes not permit overlapping invocations: if theinvoke() method is calledbefore the previousinvoke() is completed, the new invocation will notbegin until the previous invocation has completed.

ExtendedTask versus asynchronous reactives

Shiny has long supportedusing {promises}to write asynchronous observers, calcs, or outputs. You may be wonderingwhat the differences are between those techniques and this class.

Asynchronous observers, calcs, and outputs are not–and have neverbeen–designed to let a user start a long-running operation, while keepingthat very same (browser) session responsive to other interactions. Instead,they unblock other sessions, so you can take a long-running operation thatwould normally bring the entire R process to a halt and limit the blockingto just the session that started the operation. (For more details, see thesection on"The Flush Cycle".)

ExtendedTask, on the other hand, invokes an asynchronous function (thatis, a function that quickly returns a promise) and allows even that verysession to immediately unblock and carry on with other user interactions.

OpenTelemetry Integration

When anExtendedTask is created, if OpenTelemetry tracing is enabled for"reactivity" (seewithOtelCollect()), theExtendedTask will recordspans for each invocation of the task. The tracing level atinvoke() timedoes not affect whether spans are recorded; only the tracing level whencallingExtendedTask$new() matters.

The OTel span will be named based on the label created from the variable theExtendedTask is assigned to. If no label can be determined, the span willbe named⁠<anonymous>⁠. Similar to other Shiny OpenTelemetry spans, the spanwill also include source reference attributes and session ID attributes.

withOtelCollect("all", {  my_task <- ExtendedTask$new(function(...) { ... })})# Span recorded for this invocation: ExtendedTask my_taskmy_task$invoke(...)

Methods

Public methods


Methodnew()

Creates a newExtendedTask object.ExtendedTask should generally becreated either at the top of a server function, or at the top of a moduleserver function.

Usage
ExtendedTask$new(func)
Arguments
func

The long-running operation to execute. This should be anasynchronous function, meaning, it should use the{promises} package, mostlikely in conjunction with the{mirai} or{future}package. (In short, the return value offunc should be amirai,Future,promise,or something else thatpromises::as.promise() understands.)

It's also important that this logic does not read from anyreactive inputs/sources, as inputs may change after the function isinvoked; instead, if the function needs to access reactive inputs, itshould take parameters and the caller of theinvoke() method shouldread reactive inputs and pass them as arguments.


Methodinvoke()

Starts executing the long-running operation. If thisExtendedTask isalready running (meaning, a previous call toinvoke() is not yetcomplete) then enqueues this invocation until after the currentinvocation, and any already-enqueued invocation, completes.

Usage
ExtendedTask$invoke(...)
Arguments
...

Parameters to use for this invocation of the underlyingfunction. If reactive inputs are needed by the underlying function,they should be read by the caller ofinvoke and passed in asarguments.


Methodstatus()

This is a reactive read that invalidates the caller when the task'sstatus changes.

Returns one of the following values:

Usage
ExtendedTask$status()

Methodresult()

Attempts to read the results of the most recent invocation. This is areactive read that invalidates as the task's status changes.

The actual behavior differs greatly depending on the current status ofthe task:

This method is intended to be called fairly naively by any output orreactive expression that cares about the output–you just have to beaware that if the result isn't ready for whatever reason, processing willstop in much the same way asreq(FALSE) does, but when the result isready you'll get invalidated, and when you run again the result should bethere.

Note that theresult() method is generally not meant to be used withobserveEvent(),eventReactive(),bindEvent(), orisolate() as theinvalidation will be ignored.

Usage
ExtendedTask$result()

Examples

library(shiny)library(bslib)library(mirai)# Set background processes for running tasksdaemons(1)# Reset when the app is stoppedonStop(function() daemons(0))ui <- page_fluid(  titlePanel("Extended Task Demo"),  p(    'Click the button below to perform a "calculation"',    "that takes a while to perform."  ),  input_task_button("recalculate", "Recalculate"),  p(textOutput("result")))server <- function(input, output) {  rand_task <- ExtendedTask$new(function() {    mirai(      {        # Slow operation goes here        Sys.sleep(2)        sample(1:100, 1)      }    )  })  # Make button state reflect task.  # If using R >=4.1, you can do this instead:  # rand_task <- ExtendedTask$new(...) |> bind_task_button("recalculate")  bind_task_button(rand_task, "recalculate")  observeEvent(input$recalculate, {    # Invoke the extended in an observer    rand_task$invoke()  })  output$result <- renderText({    # React to updated results when the task completes    number <- rand_task$result()    paste0("Your number is ", number, ".")  })}shinyApp(ui, server)

Mock Shiny Session

Description

An R6 class suitable for testing purposes. Simulates, to theextent possible, the behavior of theShinySession class. Thesessionparameter provided to Shiny server functions and modules is an instance ofaShinySession in normal operation.

Most kinds of module and server testing do not require this class beinstantiated manually. See insteadtestServer().

In order to support advanced usage, instances ofMockShinySession areunlocked so that public methods and fields of instances may bemodified. For example, in order to test authentication workflows, theuser orgroups fields may be overridden. Modified instances ofMockShinySession may then be passed explicitly as thesession argumentoftestServer().

Public fields

env

The environment associated with the session.

returned

The value returned by the module under test.

singletons

Hardcoded as empty. Needed for rendering HTML (i.e. renderUI).

clientData

Mock client data that always returns a size for plots.

output

The shinyoutputs associated with the session.

input

The reactive inputs associated with the session.

userData

An environment initialized as empty.

progressStack

A stack of progress objects.

token

On a realShinySession, used to identify this instance in URLs.

cache

The session cache object.

appcache

The app cache object.

restoreContext

Part of bookmarking support in a realShinySession but alwaysNULL for aMockShinySession.

groups

Character vector of groups associated with an authenticateduser. AlwaysNULL for aMockShinySesion.

user

The username of an authenticated user. AlwaysNULL for aMockShinySession.

options

A list containing session-level shinyOptions.

Active bindings

files

For internal use only.

downloads

For internal use only.

closed

Deprecated inShinySession and signals an error.

session

Deprecated in ShinySession and signals an error.

request

An empty environment where the request should be. The request isn't meaningfully mocked currently.

Methods

Public methods


Methodnew()

Create a new MockShinySession.

Usage
MockShinySession$new()

MethodonFlush()

Define a callback to be invoked before a reactive flush

Usage
MockShinySession$onFlush(fun, once = TRUE)
Arguments
fun

The function to invoke

once

IfTRUE, will only run once. Otherwise, will run every time reactives are flushed.


MethodonFlushed()

Define a callback to be invoked after a reactive flush

Usage
MockShinySession$onFlushed(fun, once = TRUE)
Arguments
fun

The function to invoke

once

IfTRUE, will only run once. Otherwise, will run every time reactives are flushed.


MethodonEnded()

Define a callback to be invoked when the session ends

Usage
MockShinySession$onEnded(sessionEndedCallback)
Arguments
sessionEndedCallback

The callback to invoke when the session has ended.


MethodisEnded()

ReturnsFALSE if the session has not yet been closed

Usage
MockShinySession$isEnded()

MethodisClosed()

ReturnsFALSE if the session has not yet been closed

Usage
MockShinySession$isClosed()

Methodclose()

Closes the session

Usage
MockShinySession$close()

MethodcycleStartAction()

Unsophisticated mock implementation that merely invokes

Usage
MockShinySession$cycleStartAction(callback)
Arguments
callback

The callback to be invoked.


MethodfileUrl()

Base64-encode the given file. Needed for image rendering.

Usage
MockShinySession$fileUrl(name, file, contentType = "application/octet-stream")
Arguments
name

Not used

file

The file to be encoded

contentType

The content type of the base64-encoded string


MethodsetInputs()

Sets reactive values associated with thesession$inputsobject and flushes the reactives.

Usage
MockShinySession$setInputs(...)
Arguments
...

The inputs to set. These arguments are processed withrlang::list2() and so aredynamic. Input namesmay not be duplicated.

Examples
\dontrun{session$setInputs(x=1, y=2)}

Method.scheduleTask()

An internal method which shouldn't be used by others.Schedulescallback for execution after some number ofmillismilliseconds.

Usage
MockShinySession$.scheduleTask(millis, callback)
Arguments
millis

The number of milliseconds on which to schedule a callback

callback

The function to schedule.


Methodelapse()

Simulate the passing of time by the given number of milliseconds.

Usage
MockShinySession$elapse(millis)
Arguments
millis

The number of milliseconds to advance time.


Method.now()

An internal method which shouldn't be used by others.

Usage
MockShinySession$.now()
Returns

Elapsed time in milliseconds.


MethoddefineOutput()

An internal method which shouldn't be used by others.Defines an output in a way that sets private$currentOutputNameappropriately.

Usage
MockShinySession$defineOutput(name, func, label)
Arguments
name

The name of the output.

func

The render definition.

label

Not used.


MethodgetOutput()

An internal method which shouldn't be used by others. Forcesevaluation of any reactive dependencies of the output function.

Usage
MockShinySession$getOutput(name)
Arguments
name

The name of the output.

Returns

The return value of the function responsible for rendering theoutput.


Methodns()

Returns the given id prefixed by this namespace's id.

Usage
MockShinySession$ns(id)
Arguments
id

The id to prefix with a namespace id.

Returns

The id with a namespace prefix.


MethodflushReact()

Trigger a reactive flush right now.

Usage
MockShinySession$flushReact()

MethodmakeScope()

Create and return a namespace-specific session proxy.

Usage
MockShinySession$makeScope(namespace)
Arguments
namespace

Character vector indicating a namespace.

Returns

A new session proxy.


MethodsetEnv()

Set the environment associated with a testServer() call, butonly if it has not previously been set. This ensures that only theenvironment of the outermost module under test is the one retained. Inother words, the first assignment wins.

Usage
MockShinySession$setEnv(env)
Arguments
env

The environment to retain.

Returns

The providedenv.


MethodsetReturned()

Set the value returned by the module call and proactivelyflush. Note that this method may be called multiple times if modulesare nested. The last assignment, corresponding to an invocation ofsetReturned() in the outermost module, wins.

Usage
MockShinySession$setReturned(value)
Arguments
value

The value returned from the module

Returns

The providedvalue.


MethodgetReturned()

Get the value returned by the module call.

Usage
MockShinySession$getReturned()
Returns

The value returned by the module call


MethodgenId()

Generate a distinct character identifier for use as a proxynamespace.

Usage
MockShinySession$genId()
Returns

A character identifier unique to the current session.


MethodrootScope()

Provides a way to access the rootMockShinySession fromany descendant proxy.

Usage
MockShinySession$rootScope()
Returns

The rootMockShinySession.


MethodonUnhandledError()

Add an unhandled error callback.

Usage
MockShinySession$onUnhandledError(callback)
Arguments
callback

The callback to add, which should accept an error objectas its first argument.

Returns

A deregistration function.


MethodunhandledError()

Called by observers when a reactive expression errors.

Usage
MockShinySession$unhandledError(e, close = TRUE)
Arguments
e

An error object.

close

IfTRUE, the session will be closed after the error ishandled, defaults toFALSE.


MethodfreezeValue()

Freeze a value until the flush cycle completes.

Usage
MockShinySession$freezeValue(x, name)
Arguments
x

AReactiveValues object.

name

The name of a reactive value withinx.


MethodonSessionEnded()

Registers the given callback to be invoked when the sessionis closed (i.e. the connection to the client has been severed). Thereturn value is a function which unregisters the callback. If multiplecallbacks are registered, the order in which they are invoked is notguaranteed.

Usage
MockShinySession$onSessionEnded(sessionEndedCallback)
Arguments
sessionEndedCallback

Function to call when the session ends.


MethodregisterDownload()

Associated a downloadable file with the session.

Usage
MockShinySession$registerDownload(name, filename, contentType, content)
Arguments
name

The un-namespaced output name to associate with thedownloadable file.

filename

A string or function designating the name of the file.

contentType

A string of the content type of the file. Not used byMockShinySession.

content

A function that takes a single argument file that is afile path (string) of a nonexistent temp file, and writes the contentto that file path. (Reactive values and functions may be used from thisfunction.)


MethodgetCurrentOutputInfo()

Get information about the output that is currently beingexecuted.

Usage
MockShinySession$getCurrentOutputInfo()
Returns

A list with with thename of the output. If no output iscurrently being executed, this will returnNULL.output, orNULL if no output is currently executing.


Methodclone()

The objects of this class are cloneable with this method.

Usage
MockShinySession$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

## ------------------------------------------------## Method `MockShinySession$setInputs`## ------------------------------------------------## Not run: session$setInputs(x=1, y=2)## End(Not run)

Namespaced IDs for inputs/outputs

Description

TheNS function creates namespaced IDs out of bare IDs, by joiningthem usingns.sep as the delimiter. It is intended for use in Shinymodules. Seehttps://shiny.rstudio.com/articles/modules.html.

Usage

NS(namespace, id = NULL)ns.sep

Arguments

namespace

The character vector to use for the namespace. This can haveany length, though a single element is most common. Length 0 will cause theid to be returned without a namespace, and length 2 will beinterpreted as multiple namespaces, in increasing order of specificity(i.e. starting with the top-level namespace).

id

The id string to be namespaced (optional).

Format

An object of classcharacter of length 1.

Details

Shiny applications use IDs to identify inputs and outputs. These IDs must beunique within an application, as accidentally using the same input/output IDmore than once will result in unexpected behavior. The traditional solutionfor preventing name collisions isnamespaces; a namespace is to an IDas a directory is to a file. Use theNS function to turn a bare IDinto a namespaced one, by combining them withns.sep in between.

Value

Ifid is missing, returns a function that expects an id stringas its only argument and returns that id with the namespace prepended.

See Also

https://shiny.rstudio.com/articles/modules.html


Reporting progress (object-oriented API)

Description

Reporting progress (object-oriented API)

Reporting progress (object-oriented API)

Details

Reports progress to the user during long-running operations.

This package exposes two distinct programming APIs for working withprogress.withProgress() andsetProgress()together provide a simple function-based interface, while theProgress reference class provides an object-oriented API.

Instantiating aProgress object causes a progress panel to becreated, and it will be displayed the first time thesetmethod is called. Callingclose will cause the progress panelto be removed.

As of version 0.14, the progress indicators use Shiny's new notification API.If you want to use the old styling (for example, you may have used customizedCSS), you can usestyle="old" each time you callProgress$new(). If you don't want to set the style each timeProgress$new is called, you can instead callshinyOptions(progress.style="old") just once, inside the serverfunction.

Methods

Public methods


Methodnew()

Creates a new progress panel (but does not display it).

Usage
Progress$new(  session = getDefaultReactiveDomain(),  min = 0,  max = 1,  style = getShinyOption("progress.style", default = "notification"))
Arguments
session

The Shiny session object, as provided byshinyServer tothe server function.

min

The value that represents the starting point of the progressbar. Must be less thanmax.

max

The value that represents the end of the progress bar. Must begreater thanmin.

style

Progress display style. If"notification" (the default),the progress indicator will show using Shiny's notification API. If"old", use the same HTML and CSS used in Shiny 0.13.2 and below (thisis for backward-compatibility).


Methodset()

Updates the progress panel. When called the first time, theprogress panel is displayed.

Usage
Progress$set(value = NULL, message = NULL, detail = NULL)
Arguments
value

Single-element numeric vector; the value at which to set theprogress bar, relative tomin andmax.NULL hides the progressbar, if it is currently visible.

message

A single-element character vector; the message to bedisplayed to the user, orNULL to hide the current message (if any).

detail

A single-element character vector; the detail message to bedisplayed to the user, orNULL to hide the current detail message (ifany). The detail message will be shown with a de-emphasized appearancerelative tomessage.


Methodinc()

Likeset, this updates the progress panel. The differenceis thatinc increases the progress bar byamount, instead ofsetting it to a specific value.

Usage
Progress$inc(amount = 0.1, message = NULL, detail = NULL)
Arguments
amount

For theinc() method, a numeric value to increment theprogress bar.

message

A single-element character vector; the message to bedisplayed to the user, orNULL to hide the current message (if any).

detail

A single-element character vector; the detail message to bedisplayed to the user, orNULL to hide the current detail message (ifany). The detail message will be shown with a de-emphasized appearancerelative tomessage.


MethodgetMin()

Returns the minimum value.

Usage
Progress$getMin()

MethodgetMax()

Returns the maximum value.

Usage
Progress$getMax()

MethodgetValue()

Returns the current value.

Usage
Progress$getValue()

Methodclose()

Removes the progress panel. Future calls toset andclose will be ignored.

Usage
Progress$close()

Methodclone()

The objects of this class are cloneable with this method.

Usage
Progress$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

See Also

withProgress()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  plotOutput("plot"))server <- function(input, output, session) {  output$plot <- renderPlot({    progress <- Progress$new(session, min=1, max=15)    on.exit(progress$close())    progress$set(message = 'Calculation in progress',                 detail = 'This may take a while...')    for (i in 1:15) {      progress$set(value = i)      Sys.sleep(0.5)    }    plot(cars)  })}shinyApp(ui, server)}

Panel with absolute positioning

Description

Creates a panel whose contents are absolutely positioned.

Usage

absolutePanel(  ...,  top = NULL,  left = NULL,  right = NULL,  bottom = NULL,  width = NULL,  height = NULL,  draggable = FALSE,  fixed = FALSE,  cursor = c("auto", "move", "default", "inherit"))fixedPanel(  ...,  top = NULL,  left = NULL,  right = NULL,  bottom = NULL,  width = NULL,  height = NULL,  draggable = FALSE,  cursor = c("auto", "move", "default", "inherit"))

Arguments

...

Attributes (named arguments) or children (unnamed arguments) thatshould be included in the panel.

top

Distance between the top of the panel, and the top of the page orparent container.

left

Distance between the left side of the panel, and the left of thepage or parent container.

right

Distance between the right side of the panel, and the right ofthe page or parent container.

bottom

Distance between the bottom of the panel, and the bottom of thepage or parent container.

width

Width of the panel.

height

Height of the panel.

draggable

IfTRUE, allows the user to move the panel byclicking and dragging.

fixed

Positions the panel relative to the browser window and preventsit from being scrolled with the rest of the page.

cursor

The type of cursor that should appear when the user mouses overthe panel. Use"move" for a north-east-south-west icon,"default" for the usual cursor arrow, or"inherit" for theusual cursor behavior (including changing to an I-beam when the cursor isover text). The default is"auto", which is equivalent toifelse(draggable, "move", "inherit").

Details

TheabsolutePanel function creates a⁠<div>⁠ tag whose CSSposition is set toabsolute (or fixed iffixed = TRUE). The wayabsolute positioning works in HTML is that absolute coordinates are specifiedrelative to its nearest parent element whose position is not set tostatic (which is the default), and if no such parent is found, thenrelative to the page borders. If you're not sure what that means, just keepin mind that you may get strange results if you useabsolutePanel frominside of certain types of panels.

ThefixedPanel function is the same asabsolutePanel withfixed = TRUE.

The position (top,left,right,bottom) and size(width,height) parameters are all optional, but you shouldspecify exactly two oftop,bottom, andheight andexactly two ofleft,right, andwidth for predictableresults.

Like most other distance parameters in Shiny, the position and sizeparameters take a number (interpreted as pixels) or a valid CSS size string,such as"100px" (100 pixels) or"25%".

For arcane HTML reasons, to have the panel fill the page or parent you shouldspecify0 fortop,left,right, andbottomrather than the more obviouswidth = "100%" andheight = "100%".

Value

An HTML element or list of elements.


Action button/link

Description

Creates an action button or link whose value is initially zero, and increments by oneeach time it is pressed.

Usage

actionButton(inputId, label, icon = NULL, width = NULL, disabled = FALSE, ...)actionLink(inputId, label, icon = NULL, ...)

Arguments

inputId

Theinput slot that will be used to access the value.

label

The contents of the button or link–usually a text label, butyou could also use any other HTML, like an image.

icon

An optionalicon() to appear on the button.

width

The width of the input, e.g.'400px', or'100%';seevalidateCssUnit().

disabled

IfTRUE, the button will not be clickable. UseupdateActionButton() to dynamically enable/disable the button.

...

Named attributes to be applied to the button or link.

Server value

An integer of class"shinyActionButtonValue". This class differs fromordinary integers in that a value of 0 is considered "falsy".This implies two things:

See Also

observeEvent() andeventReactive()

Other input elements:checkboxGroupInput(),checkboxInput(),dateInput(),dateRangeInput(),fileInput(),numericInput(),passwordInput(),radioButtons(),selectInput(),sliderInput(),submitButton(),textAreaInput(),textInput(),varSelectInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  sliderInput("obs", "Number of observations", 0, 1000, 500),  actionButton("goButton", "Go!", class = "btn-success"),  plotOutput("distPlot"))server <- function(input, output) {  output$distPlot <- renderPlot({    # Take a dependency on input$goButton. This will run once initially,    # because the value changes from NULL to 0.    input$goButton    # Use isolate() to avoid dependency on input$obs    dist <- isolate(rnorm(input$obs))    hist(dist)  })}shinyApp(ui, server)}## Example of adding extra class valuesactionButton("largeButton", "Large Primary Button", class = "btn-primary btn-lg")actionLink("infoLink", "Information Link", class = "btn-info")

Resource Publishing

Description

Add, remove, or list directory of static resources to Shiny's web server,with the given path prefix. Primarily intended for package authors to makesupporting JavaScript/CSS files available to their components.

Usage

addResourcePath(prefix, directoryPath)resourcePaths()removeResourcePath(prefix)

Arguments

prefix

The URL prefix (without slashes). Valid characters are a-z,A-Z, 0-9, hyphen, period, and underscore. For example, a value of 'foo'means that any request paths that begin with '/foo' will be mapped to thegiven directory.

directoryPath

The directory that contains the static resources to beserved.

Details

Shiny provides two ways of serving static files (i.e., resources):

  1. Static files under the⁠www/⁠ directory are automatically made availableunder a request path that begins with/.

  2. addResourcePath() makes static files in adirectoryPath availableunder a request path that begins withprefix.

The second approach is primarily intended for package authors to makesupporting JavaScript/CSS files available to their components.

Tools for managing static resources published by Shiny's web server:

See Also

singleton()

Examples

addResourcePath('datasets', system.file('data', package='datasets'))resourcePaths()removeResourcePath('datasets')resourcePaths()# make sure all resources are removedlapply(names(resourcePaths()), removeResourcePath)

Apply input handlers to raw input values

Description

The purpose of this function is to make it possible for external packages totest Shiny inputs. It takes a named list of raw input values, applies inputhandlers to those values, and then returns a named list of the processedvalues.

Usage

applyInputHandlers(inputs, shinysession = getDefaultReactiveDomain())

Arguments

inputs

A named list of input values.

shinysession

A Shiny session object.

Details

The raw input values should be in a named list. Some values may have nameslike"x:shiny.date". This function would apply the"shiny.date"input handler to the value, and then rename the result to"x", in theoutput.

See Also

registerInputHandler


Add caching with reactivity to an object

Description

bindCache() adds cachingreactive() expressions and⁠render*⁠ functions(likerenderText(),renderTable(), ...).

Ordinaryreactive() expressions automatically cache theirmost recentvalue, which helps to avoid redundant computation in downstream reactives.bindCache() will cache all previous values (as long as they fit in thecache) and they can be shared across user sessions. This allowsbindCache() to dramatically improve performance when used correctly.

Usage

bindCache(x, ..., cache = "app")

Arguments

x

The object to add caching to.

...

One or more expressions to use in the caching key.

cache

The scope of the cache, or a cache object. This can be"app"(the default),"session", or a cache object like acachem::cache_disk(). See the Cache Scoping section for more information.

Details

bindCache() requires one or more expressions that are used to generate acache key, which is used to determine if a computation has occurredbefore and hence can be retrieved from the cache. If you're familiar with theconcept of memoizing pure functions (e.g., thememoise package), youcan think of the cache key as the input(s) to a pure function. As such, oneshould take care to make sure the use ofbindCache() ispure in the samesense, namely:

  1. For a given key, the return value is always the same.

  2. Evaluation has no side-effects.

In the example here, thebindCache() key consists ofinput$x andinput$y combined, and the value isinput$x * input$y. In this simpleexample, for any given key, there is only one possible returned value.

r <- reactive({ input$x * input$y }) %>%  bindCache(input$x, input$y)

The largest performance improvements occur when the cache key is fast tocompute and the reactive expression is slow to compute. To see if the valueshould be computed, a cached reactive evaluates the key, and then serializesand hashes the result. If the resulting hashed key is in the cache, then thecached reactive simply retrieves the previously calculated value and returnsit; if not, then the value is computed and the result is stored in the cachebefore being returned.

To compute the cache key,bindCache() hashes the contents of..., so it'sbest to avoid including large objects in a cache key since that can result inslow hashing. It's also best to avoid reference objects like environments andR6 objects, since the serialization of these objects may not capture relevantchanges.

If you want to use a large object as part of a cache key, it may make senseto do some sort of reduction on the data that still captures informationabout whether a value can be retrieved from the cache. For example, if youhave a large data set with timestamps, it might make sense to extract themost recent timestamp and return that. Then, instead of hashing the entiredata object, the cached reactive only needs to hash the timestamp.

r <- reactive({ compute(bigdata()) } %>%  bindCache({ extract_most_recent_time(bigdata()) })

For computations that are very slow, it often makes sense to pairbindCache() withbindEvent() so that no computation is performed untilthe user explicitly requests it (for more, see the Details section ofbindEvent()).

Cache keys and reactivity

Because thevalue expression (from the originalreactive()) iscached, it is not necessarily re-executed when someone retrieves a value,and therefore it can't be used to decide what objects to take reactivedependencies on. Instead, thekey is used to figure out which objectsto take reactive dependencies on. In short, the key expression is reactive,and value expression is no longer reactive.

Here's an example of what not to do: if the key isinput$x and the valueexpression is fromreactive({input$x + input$y}), then the resultingcached reactive will only take a reactive dependency oninput$x – itwon't recompute{input$x + input$y} when justinput$y changes.Moreover, the cache won't useinput$y as part of the key, and so it couldreturn incorrect values in the future when it retrieves values from thecache. (See the examples below for an example of this.)

A better cache key would be something like⁠input$x, input$y⁠. This doestwo things: it ensures that a reactive dependency is taken on bothinput$x andinput$y, and it also makes sure that both values arerepresented in the cache key.

In general,key should use the same reactive inputs asvalue, but thecomputation should be simpler. If there are other (non-reactive) valuesthat are consumed, such as external data sources, they should be used inthekey as well. Note that if thekey is large, it can make sense to dosome sort of reduction on it so that the serialization and hashing of thecache key is not too expensive.

Remember that the key isreactive, so it is not re-executed every singletime that someone accesses the cached reactive. It is only re-executed ifit has been invalidated by one of the reactives it depends on. Forexample, suppose we have this cached reactive:

r <- reactive({ input$x * input$y }) %>% bindCache(input$x, input$y)

In this case, the key expression is essentiallyreactive(list(input$x, input$y)) (there's a bit more to it, but that's a good enoughapproximation). The first timer() is called, it executes the key, thenfails to find it in the cache, so it executes the value expression,{ input$x + input$y }. Ifr() is called again, then it does not need tore-execute the key expression, because it has not been invalidated via achange toinput$x orinput$y; it simply returns the previous value.However, ifinput$x orinput$y changes, then the reactive expression willbe invalidated, and the next time that someone callsr(), the keyexpression will need to be re-executed.

Note that if the cached reactive is passed tobindEvent(), then the keyexpression will no longer be reactive; instead, the event expression will bereactive.

Cache scope

By default, whenbindCache() is used, it is scoped to the runningapplication. That means that it shares a cache with all user sessionsconnected to the application (within the R process). This is done with thecache parameter's default value,"app".

With an app-level cache scope, one user can benefit from the work done foranother user's session. In most cases, this is the best way to getperformance improvements from caching. However, in some cases, this couldleak information between sessions. For example, if the cache key does notfully encompass the inputs used by the value, then data could leak betweenthe sessions. Or if a user sees that a cached reactive returns its valuevery quickly, they may be able to infer that someone else has already usedit with the same values.

It is also possible to scope the cache to the session, withcache="session". This removes the risk of information leaking betweensessions, but then one session cannot benefit from computations performed inanother session.

It is possible to pass in caching objects directly tobindCache(). This can be useful if, for example, you want to use aparticular type of cache with specific cached reactives, or if you want touse acachem::cache_disk() that is shared across multiple processes andpersists beyond the current R session.

To use different settings for an application-scoped cache, you can callshinyOptions() at the top of your app.R, server.R, orglobal.R. For example, this will create a cache with 500 MB of spaceinstead of the default 200 MB:

shinyOptions(cache = cachem::cache_mem(max_size = 500e6))

To use different settings for a session-scoped cache, you can setsession$cache at the top of your server function. By default, it willcreate a 200 MB memory cache for each session, but you can replace it withsomething different. To use the session-scoped cache, you must also callbindCache() withcache="session". This will create a 100 MB cache forthe session:

function(input, output, session) {  session$cache <- cachem::cache_mem(max_size = 100e6)  ...}

If you want to use a cache that is shared across multiple R processes, youcan use acachem::cache_disk(). You can create a application-level sharedcache by putting this at the top of your app.R, server.R, or global.R:

shinyOptions(cache = cachem::cache_disk(file.path(dirname(tempdir()), "myapp-cache")))

This will create a subdirectory in your system temp directory namedmyapp-cache (replacemyapp-cache with a unique name ofyour choosing). On most platforms, this directory will be removed whenyour system reboots. This cache will persist across multiple starts andstops of the R process, as long as you do not reboot.

To have the cache persist even across multiple reboots, you can create thecache in a location outside of the temp directory. For example, it couldbe a subdirectory of the application:

shinyOptions(cache = cachem::cache_disk("./myapp-cache"))

In this case, resetting the cache will have to be done manually, by deletingthe directory.

You can also scope a cache to just one item, or selected items. To do that,create acachem::cache_mem() orcachem::cache_disk(), and pass itas thecache argument ofbindCache().

Computing cache keys

The actual cache key that is used internally takes value from evaluatingthe key expression(s) (from the... arguments) and combines it with the(unevaluated) value expression.

This means that if there are two cached reactives which have the sameresult from evaluating the key, but different value expressions, then theywill not need to worry about collisions.

However, if two cached reactives have identical key and value expressionsexpressions, they will share the cached values. This is useful when usingcache="app": there may be multiple user sessions which create separatecached reactive objects (because they are created from the same code in theserver function, but the server function is executed once for each usersession), and those cached reactive objects across sessions can sharevalues in the cache.

Async with cached reactives

With a cached reactive expression, the key and/or value expression can beasynchronous. In other words, they can be promises — not regular Rpromises, but rather objects provided by thepromises package, whichare similar to promises in JavaScript. (Seepromises::promise() for moreinformation.) You can also usemirai::mirai() orfuture::future()objects to run code in a separate process or even on a remote machine.

If the value returns a promise, then anything that consumes the cachedreactive must expect it to return a promise.

Similarly, if the key is a promise (in other words, if it is asynchronous),then the entire cached reactive must be asynchronous, since the key must becomputed asynchronously before it knows whether to compute the value or thevalue is retrieved from the cache. Anything that consumes the cachedreactive must therefore expect it to return a promise.

Developing render functions for caching

If you've implemented your own⁠render*()⁠ function, it may just work withbindCache(), but it is possible that you will need to make somemodifications. These modifications involve helpingbindCache() avoidcache collisions, dealing with internal state that may be set by the,render function, and modifying the data as it goes in and comes out ofthe cache.

You may need to provide acacheHint tocreateRenderFunction() (orhtmlwidgets::shinyRenderWidget(), if you've authored an htmlwidget) inorder forbindCache() to correctly compute a cache key.

The potential problem is a cache collision. Consider the following:

output$x1 <- renderText({ input$x }) %>% bindCache(input$x)output$x2 <- renderText({ input$x * 2 }) %>% bindCache(input$x)

Bothoutput$x1 andoutput$x2 useinput$x as part of their cache key,but if it were the only thing used in the cache key, then the two outputswould have a cache collision, and they would have the same output. To avoidthis, acache hint is automatically added whenrenderText() callscreateRenderFunction(). The cache hint is used as part of the actualcache key, in addition to the one passed tobindCache() by the user. Thecache hint can be viewed by calling the internal Shiny functionextractCacheHint():

r <- renderText({ input$x })shiny:::extractCacheHint(r)

This returns a nested list containing an item,⁠$origUserFunc$body⁠, whichin this case is the expression which was passed torenderText():{ input$x }. This (quoted) expression is mixed into the actual cachekey, and it is howoutput$x1 does not have collisions withoutput$x2.

For most developers of render functions, nothing extra needs to be done;the automatic inference of the cache hint is sufficient. Again, you cancheck it by callingshiny:::extractCacheHint(), and by testing therender function for cache collisions in a real application.

In some cases, however, the automatic cache hint inference is notsufficient, and it is necessary to provide a cache hint. This is trueforrenderPrint(). UnlikerenderText(), it wraps the user-providedexpression in another function, before passing it tocreateRenderFunction()(instead ofcreateRenderFunction()). Because the user code is wrapped inanother function,createRenderFunction() is not able to automaticallyextract the user-provided code and use it in the cache key. Instead,renderPrint callscreateRenderFunction(), it explicitly passes along acacheHint, which includes a label and the original user expression.

In general, if you need to provide acacheHint, it is best practice toprovide alabel id, the user'sexpr, as well as any other argumentsthat may influence the final value.

Forhtmlwidgets, it will try to automatically infer a cache hint;again, you can inspect the cache hint withshiny:::extractCacheHint() andalso test it in an application. If you do need to explicitly provide acache hint, pass it toshinyRenderWidget. For example:

renderMyWidget <- function(expr) {  q <- rlang::enquo0(expr)  htmlwidgets::shinyRenderWidget(    q,    myWidgetOutput,    quoted = TRUE,    cacheHint = list(label = "myWidget", userQuo = q)  )}

If yourrender function sets any internal state, you may find it usefulin your call tocreateRenderFunction() to usethecacheWriteHook and/orcacheReadHook parameters. These hooks arefunctions that run just before the object is stored in the cache, and justafter the object is retrieved from the cache. They can modify the datathat is stored and retrieved; this can be useful if extra information needsto be stored in the cache. They can also be used to modify the state of theapplication; for example, it can callcreateWebDependency() to makeJS/CSS resources available if the cached object is loaded in a different Rprocess. (See the source ofhtmlwidgets::shinyRenderWidget for an exampleof this.)

Uncacheable objects

Some render functions cannot be cached, typically because they have sideeffects or modify some external state, and they must re-execute each timein order to work properly.

For developers of such code, they should callcreateRenderFunction() (ormarkRenderFunction()) withcacheHint = FALSE.

Caching withrenderPlot()

WhenbindCache() is used withrenderPlot(), theheight andwidthpassed to the originalrenderPlot() are ignored. They are superseded bysizePolicy argument passed to 'bindCache. The default is:

sizePolicy = sizeGrowthRatio(width = 400, height = 400, growthRate = 1.2)

sizePolicy must be a function that takes a two-element numeric vector asinput, representing the width and height of the⁠<img>⁠ element in thebrowser window, and it must return a two-element numeric vector, representingthe pixel dimensions of the plot to generate. The purpose is to round theactual pixel dimensions from the browser to some other dimensions, so thatthis will not generate and cache images of every possible pixel dimension.SeesizeGrowthRatio() for more information on the default sizing policy.

See Also

bindEvent(),renderCachedPlot() for caching plots.

Examples

## Not run: rc <- bindCache(  x = reactive({    Sys.sleep(2)   # Pretend this is expensive    input$x * 100  }),  input$x)# Can make it prettier with the %>% operatorlibrary(magrittr)rc <- reactive({  Sys.sleep(2)  input$x * 100}) %>%  bindCache(input$x)## End(Not run)## Only run app examples in interactive R sessionsif (interactive()) {# Basic exampleshinyApp(  ui = fluidPage(    sliderInput("x", "x", 1, 10, 5),    sliderInput("y", "y", 1, 10, 5),    div("x * y: "),    verbatimTextOutput("txt")  ),  server = function(input, output) {    r <- reactive({      # The value expression is an _expensive_ computation      message("Doing expensive computation...")      Sys.sleep(2)      input$x * input$y    }) %>%      bindCache(input$x, input$y)    output$txt <- renderText(r())  })# Caching renderTextshinyApp(  ui = fluidPage(    sliderInput("x", "x", 1, 10, 5),    sliderInput("y", "y", 1, 10, 5),    div("x * y: "),    verbatimTextOutput("txt")  ),  server = function(input, output) {    output$txt <- renderText({      message("Doing expensive computation...")      Sys.sleep(2)      input$x * input$y    }) %>%      bindCache(input$x, input$y)  })# Demo of using events and caching with an actionButtonshinyApp(  ui = fluidPage(    sliderInput("x", "x", 1, 10, 5),    sliderInput("y", "y", 1, 10, 5),    actionButton("go", "Go"),    div("x * y: "),    verbatimTextOutput("txt")  ),  server = function(input, output) {    r <- reactive({      message("Doing expensive computation...")      Sys.sleep(2)      input$x * input$y    }) %>%      bindCache(input$x, input$y) %>%      bindEvent(input$go)      # The cached, eventified reactive takes a reactive dependency on      # input$go, but doesn't use it for the cache key. It uses input$x and      # input$y for the cache key, but doesn't take a reactive dependency on      # them, because the reactive dependency is superseded by addEvent().    output$txt <- renderText(r())  })}

Make an object respond only to specified reactive events

Description

Modify an object to respond to "event-like" reactive inputs, values, andexpressions.bindEvent() can be used with reactive expressions, renderfunctions, and observers. The resulting object takes a reactive dependency onthe... arguments, and not on the original object's code. This can, forexample, be used to make an observer execute only when a button is pressed.

bindEvent() was added in Shiny 1.6.0. When it is used withreactive() andobserve(), it does the same thing aseventReactive() andobserveEvent(). However,bindEvent() is more flexible: it can be combinedwithbindCache(), and it can also be used withrender functions (likerenderText() andrenderPlot()).

Usage

bindEvent(  x,  ...,  ignoreNULL = TRUE,  ignoreInit = FALSE,  once = FALSE,  label = NULL)

Arguments

x

An object to wrap so that is triggered only when a the specifiedevent occurs.

...

One or more expressions that represents the event; this can be asimple reactive value likeinput$click, a call to a reactive expressionlikedataset(), or even a complex expression inside curly braces. Ifthere are multiple expressions in the..., then it will take a dependencyon all of them.

ignoreNULL

Whether the action should be triggered (or valuecalculated) when the input isNULL. See Details.

ignoreInit

IfTRUE, then, when the eventified object is firstcreated/initialized, don't trigger the action or (compute the value). Thedefault isFALSE. See Details.

once

Used only for observers. Whether thisobserver should beimmediately destroyed after the first time that the code in the observer isrun. This pattern is useful when you want to subscribe to a event thatshould only happen once.

label

A label for the observer or reactive, useful for debugging.

Details

Shiny's reactive programming framework is primarily designed for calculatedvalues (reactive expressions) and side-effect-causing actions (observers)that respond toany of their inputs changing. That's often what isdesired in Shiny apps, but not always: sometimes you want to wait for aspecific action to be taken from the user, like clicking anactionButton(), before calculating an expression or taking an action. Areactive value or expression that is used to trigger other calculations inthis way is called anevent.

These situations demand a more imperative, "event handling" style ofprogramming that is possible–but not particularly intuitive–using thereactive programming primitivesobserve() andisolate().bindEvent()provides a straightforward API for event handling that wrapsobserve andisolate.

The... arguments are captured as expressions and combined into anevent expression. When this event expression is invalidated (when itsupstream reactive inputs change), that is anevent, and it will causethe original object's code to execute.

UsebindEvent() withobserve() whenever you want toperform an actionin response to an event. (This does the same thing asobserveEvent(),which was available in Shiny prior to version 1.6.0.) Note that"recalculate a value" does not generally count as performing an action –usereactive() for that.

UsebindEvent() withreactive() to create acalculated value thatonly updates in response to an event. This is just like a normalreactive expression except it ignores all the usual invalidations thatcome from its reactive dependencies; it only invalidates in response to thegiven event. (This does the same thing aseventReactive(), which wasavailable in Shiny prior to version 1.6.0.)

bindEvent() is often used withbindCache().

ignoreNULL and ignoreInit

bindEvent() takes anignoreNULL parameter that affects behavior whenthe event expression evaluates toNULL (or in the special case of anactionButton(),0). In these cases, ifignoreNULL isTRUE, then itwill raise a silentvalidation error. This is useful behaviorif you don't want to do the action or calculation when your app firststarts, but wait for the user to initiate the action first (like a "Submit"button); whereasignoreNULL=FALSE is desirable if you want to initiallyperform the action/calculation and just let the user re-initiate it (like a"Recalculate" button).

bindEvent() also takes anignoreInit argument. By default, reactiveexpressions and observers will run on the first reactive flush after theyare created (except if, at that moment, the event expression evaluates toNULL andignoreNULL isTRUE). But when responding to a click of anaction button, it may often be useful to setignoreInit toTRUE. Forexample, if you're setting up an observer to respond to a dynamicallycreated button, thenignoreInit = TRUE will guarantee that the actionwill only be triggered when the button is actually clicked, instead of alsobeing triggered when it is created/initialized. Similarly, if you'resetting up a reactive that responds to a dynamically created button used torefresh some data (which is then returned by thatreactive), then youshould usereactive(...) %>% bindEvent(..., ignoreInit = TRUE) if youwant to let the user decide if/when they want to refresh the data (since,depending on the app, this may be a computationally expensive operation).

Even thoughignoreNULL andignoreInit can be used for similar purposesthey are independent from one another. Here's the result of combiningthese:

ignoreNULL = TRUE andignoreInit = FALSE

This is the default. This combination means that reactive/observer codewill run every time that event expression is notNULL. If, at the time of creation, the event expression happenstonot beNULL, then the code runs.

ignoreNULL = FALSE andignoreInit = FALSE

This combination means that reactive/observer code willrun every time no matter what.

ignoreNULL = FALSE andignoreInit = TRUE

This combination means that reactive/observer code willnot run at the time of creation (becauseignoreInit = TRUE),but it will run every other time.

ignoreNULL = TRUE andignoreInit = TRUE

This combination means that reactive/observer code willnot at the time of creation (becauseignoreInit = TRUE).After that, the reactive/observer code will run every time thatthe event expression is notNULL.

Types of objects

bindEvent() can be used with reactive expressions, observers, and shinyrender functions.

WhenbindEvent() is used withreactive(), it creates a new reactiveexpression object.

WhenbindEvent() is used withobserve(), it alters the observer inplace. It can only be used with observers which have not yet executed.

Combining events and caching

In many cases, it makes sense to usebindEvent() along withbindCache(), because they each can reduce the amount of work done on theserver. For example, you could havesliderInputsx andy and areactive() that performs a time-consuming operation with those values.UsingbindCache() can speed things up, especially if there are multipleusers. But it might make sense to also not do the computation until theuser sets bothx andy, and then clicks on anactionButton namedgo.

To use both caching and events, the object should first be passed tobindCache(), thenbindEvent(). For example:

r <- reactive({   Sys.sleep(2)  # Pretend this is an expensive computation   input$x * input$y }) %>% bindCache(input$x, input$y) %>% bindEvent(input$go)

Anything that consumesr() will take a reactive dependency on the eventexpression given tobindEvent(), and not the cache key expression given tobindCache(). In this case, it is justinput$go.


Create a button for bookmarking/sharing

Description

AbookmarkButton is aactionButton() with a default labelthat consists of a link icon and the text "Bookmark...". It is meant to beused for bookmarking state.

Usage

bookmarkButton(  label = "Bookmark...",  icon = shiny::icon("link", lib = "glyphicon"),  title = "Bookmark this application's state and get a URL for sharing.",  ...,  id = "._bookmark_")

Arguments

label

The contents of the button or link–usually a text label, butyou could also use any other HTML, like an image.

icon

An optionalicon() to appear on the button.

title

A tooltip that is shown when the mouse cursor hovers over thebutton.

...

Named attributes to be applied to the button or link.

id

An ID for the bookmark button. The only time it is necessary to setthe ID unless you have more than one bookmark button in your application.If you specify an input ID, it should be excluded from bookmarking withsetBookmarkExclude(), and you must create an observer thatdoes the bookmarking when the button is pressed. See the examples below.

See Also

enableBookmarking() for more examples.

Examples

## Only run these examples in interactive sessionsif (interactive()) {# This example shows how to use multiple bookmark buttons. If you only need# a single bookmark button, see examples in ?enableBookmarking.ui <- function(request) {  fluidPage(    tabsetPanel(id = "tabs",      tabPanel("One",        checkboxInput("chk1", "Checkbox 1"),        bookmarkButton(id = "bookmark1")      ),      tabPanel("Two",        checkboxInput("chk2", "Checkbox 2"),        bookmarkButton(id = "bookmark2")      )    )  )}server <- function(input, output, session) {  # Need to exclude the buttons from themselves being bookmarked  setBookmarkExclude(c("bookmark1", "bookmark2"))  # Trigger bookmarking with either button  observeEvent(input$bookmark1, {    session$doBookmark()  })  observeEvent(input$bookmark2, {    session$doBookmark()  })}enableBookmarking(store = "url")shinyApp(ui, server)}

Bootstrap libraries

Description

This function defines a set of web dependencies necessary for using Bootstrapcomponents in a web page.

Usage

bootstrapLib(theme = NULL)

Arguments

theme

One of the following:

  • NULL (the default), which implies a "stock" build of Bootstrap 3.

  • Abslib::bs_theme() object. This can be used to replace a stockbuild of Bootstrap 3 with a customized version of Bootstrap 3 or higher.

  • A character string pointing to an alternative Bootstrap stylesheet(normally a css file within the www directory, e.g.www/bootstrap.css).

Details

It isn't necessary to call this function if you usebootstrapPage() orothers which usebootstrapPage, suchfluidPage(),navbarPage(),fillPage(), etc, because they already include the Bootstrap web dependencies.


Create a Bootstrap page

Description

Create a Shiny UI page that loads the CSS and JavaScript forBootstrap, and has no content in the pagebody (other than what you provide).

Usage

bootstrapPage(..., title = NULL, theme = NULL, lang = NULL)basicPage(...)

Arguments

...

The contents of the document body.

title

The browser window title (defaults to the host URL of the page)

theme

One of the following:

  • NULL (the default), which implies a "stock" build of Bootstrap 3.

  • Abslib::bs_theme() object. This can be used to replace a stockbuild of Bootstrap 3 with a customized version of Bootstrap 3 or higher.

  • A character string pointing to an alternative Bootstrap stylesheet(normally a css file within the www directory, e.g.www/bootstrap.css).

lang

ISO 639-1 language code for the HTML page, such as "en" or "ko".This will be used as the lang in the<html> tag, as in<html lang="en">.The default (NULL) results in an empty string.

Details

This function is primarily intended for users who are proficient in HTML/CSS,and know how to lay out pages in Bootstrap. Most applications should usefluidPage() along with layout functions likefluidRow() andsidebarLayout().

Value

A UI definition that can be passed to theshinyUI function.

Note

ThebasicPage function is deprecated, you should use thefluidPage() function instead.

See Also

fluidPage(),fixedPage()


Create an object representing brushing options

Description

This generates an object representing brushing options, to be passed as thebrush argument ofimageOutput() orplotOutput().

Usage

brushOpts(  id,  fill = "#9cf",  stroke = "#036",  opacity = 0.25,  delay = 300,  delayType = c("debounce", "throttle"),  clip = TRUE,  direction = c("xy", "x", "y"),  resetOnNew = FALSE)

Arguments

id

Input value name. For example, if the value is"plot_brush",then the coordinates will be available asinput$plot_brush. MultipleimageOutput/plotOutput calls may share the sameidvalue; brushing one image or plot will cause any other brushes with thesameid to disappear.

fill

Fill color of the brush. If'auto', it derives from the linkcolor of the plot's HTML container (ifthematic is enabled, andaccentis a non-'auto' value, that color is used instead).

stroke

Outline color of the brush. If'auto', it derives from theforeground color of the plot's HTML container (ifthematic is enabled,andfg is a non-'auto' value, that color is used instead).

opacity

Opacity of the brush

delay

How long to delay (in milliseconds) when debouncing orthrottling, before sending the brush data to the server.

delayType

The type of algorithm for limiting the number of brushevents. Use"throttle" to limit the number of brush events to oneeverydelay milliseconds. Use"debounce" to suspend eventswhile the cursor is moving, and wait until the cursor has been at rest fordelay milliseconds before sending an event.

clip

Should the brush area be clipped to the plotting area? If FALSE,then the user will be able to brush outside the plotting area, as long asit is still inside the image.

direction

The direction for brushing. If"xy", the brush can bedrawn and moved in both x and y directions. If"x", or"y",the brush wil work horizontally or vertically.

resetOnNew

When a new image is sent to the browser (viarenderImage()), should the brush be reset? The default,FALSE, is useful if you want to update the plot while keeping thebrush. UsingTRUE is useful if you want to clear the brush wheneverthe plot is updated.

See Also

clickOpts() for clicking events.


Find rows of data selected on an interactive plot.

Description

brushedPoints() returns rows from a data frame which are under a brush.nearPoints() returns rows from a data frame which are near a click, hover,or double-click. Alternatively, setallRows = TRUE to return all rows fromthe input data with an additional columnselected_ that indicates whichrows of the would be selected.

Usage

brushedPoints(  df,  brush,  xvar = NULL,  yvar = NULL,  panelvar1 = NULL,  panelvar2 = NULL,  allRows = FALSE)nearPoints(  df,  coordinfo,  xvar = NULL,  yvar = NULL,  panelvar1 = NULL,  panelvar2 = NULL,  threshold = 5,  maxpoints = NULL,  addDist = FALSE,  allRows = FALSE)

Arguments

df

A data frame from which to select rows.

brush,coordinfo

The data from a brush or click/dblclick/hover evente.g.input$plot_brush,input$plot_click.

xvar,yvar

A string giving the name of the variable on the x or y axis.These are only required for base graphics, and must be the name ofa column indf.

panelvar1,panelvar2

A string giving the name of a panel variable.For expert use only; in most cases these will be automaticallyderived from the ggplot2 spec.

allRows

IfFALSE (the default) return a data frame containingthe selected rows. IfTRUE, the input data frame will have a newcolumn,selected_, which indicates whether the row was selected or not.

threshold

A maximum distance (in pixels) to the pointer location.Rows in the data frame will be selected if the distance to the pointer isless thanthreshold.

maxpoints

Maximum number of rows to return. IfNULL (the default),will return all rows within the threshold distance.

addDist

If TRUE, add a column nameddist_ that contains thedistance from the coordinate to the point, in pixels. When no pointerevent has yet occurred, the value ofdist_ will beNA.

Value

A data frame based ondf, containing the observations selected by thebrush or near the click event. FornearPoints(), the rows will be sortedby distance to the event.

IfallRows = TRUE, then all rows will returned, along with a newselected_ column that indicates whether or not the point was selected.The output fromnearPoints() will no longer be sorted, but you cansetaddDist = TRUE to get an additional column that gives the pixeldistance to the pointer.

ggplot2

For plots created with ggplot2, it is not necessary to specify thecolumn names toxvar,yvar,panelvar1, andpanelvar2 as thatinformation can be automatically derived from the plot specification.

Note, however, that this will not work if you use a computed column, like⁠aes(speed/2, dist))⁠. Instead, we recommend that you modify the datafirst, and then make the plot with "raw" columns in the modified data.

Brushing

If x or y column is a factor, then it will be coerced to an integer vector.If it is a character vector, then it will be coerced to a factor and theninteger vector. This means that the brush will be considered to cover agiven character/factor value when it covers the center value.

If the brush is operating in just the x or y directions (e.g., withbrushOpts(direction = "x"), then this function will filter out pointsusing just the x or y variable, whichever is appropriate.

See Also

plotOutput() for example usage.

Examples

## Not run: # Note that in practice, these examples would need to go in reactives# or observers.# This would select all points within 5 pixels of the clicknearPoints(mtcars, input$plot_click)# Select just the nearest point within 10 pixels of the clicknearPoints(mtcars, input$plot_click, threshold = 10, maxpoints = 1)## End(Not run)

Customize busy indicator options

Description

Shiny automatically includes busy indicators, which more specifically means:

  1. Calculating/recalculating outputs have a spinner overlay.

  2. Outputs fade out/in when recalculating.

  3. When no outputs are calculating/recalculating, but Shiny is busydoing something else (e.g., a download, side-effect, etc), a page-levelpulsing banner is shown.

This function allows you to customize the appearance of these busy indicatorsby including the result of this function inside the app's UI. Note that,unlessspinner_selector (orfade_selector) is specified, the spinner/fadecustomization applies to the parent element. If the customization shouldinstead apply to the entire page, setspinner_selector = 'html' andfade_selector = 'html'.

Usage

busyIndicatorOptions(  ...,  spinner_type = NULL,  spinner_color = NULL,  spinner_size = NULL,  spinner_delay = NULL,  spinner_selector = NULL,  fade_opacity = NULL,  fade_selector = NULL,  pulse_background = NULL,  pulse_height = NULL,  pulse_speed = NULL)

Arguments

...

Currently ignored.

spinner_type

The type of spinner. Pre-bundled types include:'ring', 'ring2', 'ring3', 'bars', 'bars2', 'bars3', 'pulse', 'pulse2', 'pulse3', 'dots', 'dots2', 'dots3'.

A path to a local SVG file can also be provided. The SVG should adhere tothe following rules:

  • The SVG itself should contain the animation.

  • It should avoid absolute sizes (the spinner's containing DOM elementsize is set in CSS byspinner_size, so it should fill that container).

  • It should avoid setting absolute colors (the spinner's containing DOM elementcolor is set in CSS byspinner_color, so it should inherit that color).

spinner_color

The color of the spinner. This can be any valid CSScolor. Defaults to the app's "primary" color if Bootstrap is on the page.

spinner_size

The size of the spinner. This can be any valid CSS size.

spinner_delay

The amount of time to wait before showing the spinner.This can be any valid CSS time and can be useful for not showing the spinnerif the computation finishes quickly.

spinner_selector

A character string containing a CSS selector forscoping the spinner customization. The default (NULL) will apply thespinner customization to the parent element of the spinner.

fade_opacity

The opacity (a number between 0 and 1) for recalculatingoutput. Set to 1 to "disable" the fade.

fade_selector

A character string containing a CSS selector forscoping the spinner customization. The default (NULL) will apply thespinner customization to the parent element of the spinner.

pulse_background

A CSS background definition for the pulse. Thedefault uses alinear-gradientof the theme's indigo, purple, and pink colors.

pulse_height

The height of the pulsing banner. This can be any validCSS size.

pulse_speed

The speed of the pulsing banner. This can be any valid CSStime.

See Also

useBusyIndicators() to disable/enable busy indicators.

Examples

library(bslib)card_ui <- function(id, spinner_type = id) {  card(    busyIndicatorOptions(spinner_type = spinner_type),    card_header(paste("Spinner:", spinner_type)),    plotOutput(shiny::NS(id, "plot"))  )}card_server <- function(id, simulate = reactive()) {  moduleServer(    id = id,    function(input, output, session) {      output$plot <- renderPlot({        Sys.sleep(1)        simulate()        plot(x = rnorm(100), y = rnorm(100))      })    }  )}ui <- page_fillable(  useBusyIndicators(),  input_task_button("simulate", "Simulate", icon = icon("refresh")),  layout_columns(    card_ui("ring"),    card_ui("bars"),    card_ui("dots"),    card_ui("pulse"),    col_widths = 6  ))server <- function(input, output, session) {  simulate <- reactive(input$simulate)  card_server("ring", simulate)  card_server("bars", simulate)  card_server("dots", simulate)  card_server("pulse", simulate)}shinyApp(ui, server)

Invoke a Shiny module

Description

Note: As of Shiny 1.5.0, we recommend usingmoduleServer() instead ofcallModule(), because the syntax is a little easierto understand, and modules created withmoduleServer can be tested withtestServer().

Usage

callModule(module, id, ..., session = getDefaultReactiveDomain())

Arguments

module

A Shiny module server function

id

An ID string that corresponds with the ID used to call the module'sUI function

...

Additional parameters to pass to module server function

session

Session from which to make a child scope (the default shouldalmost always be used)

Value

The return value, if any, from executing the module server function


Checkbox Group Input Control

Description

Create a group of checkboxes that can be used to toggle multiple choicesindependently. The server will receive the input as a character vector of theselected values.

Usage

checkboxGroupInput(  inputId,  label,  choices = NULL,  selected = NULL,  inline = FALSE,  width = NULL,  choiceNames = NULL,  choiceValues = NULL)

Arguments

inputId

Theinput slot that will be used to access the value.

label

Display label for the control, orNULL for no label.

choices

List of values to show checkboxes for. If elements of the listare named then that name rather than the value is displayed to the user. Ifthis argument is provided, thenchoiceNames andchoiceValuesmust not be provided, and vice-versa. The values should be strings; othertypes (such as logicals and numbers) will be coerced to strings.

selected

The values that should be initially selected, if any.

inline

IfTRUE, render the choices inline (i.e. horizontally)

width

The width of the input, e.g.'400px', or'100%';seevalidateCssUnit().

choiceNames,choiceValues

List of names and values, respectively,that are displayed to the user in the app and correspond to the eachchoice (for this reason,choiceNames andchoiceValuesmust have the same length). If either of these arguments isprovided, then the othermust be provided andchoicesmust not be provided. The advantage of using both of these overa named list forchoices is thatchoiceNames allows anytype of UI object to be passed through (tag objects, icons, HTML code,...), instead of just simple text. See Examples.

Value

A list of HTML elements that can be added to a UI definition.

Server value

Character vector of values corresponding to the boxes that are checked.

See Also

checkboxInput(),updateCheckboxGroupInput()

Other input elements:actionButton(),checkboxInput(),dateInput(),dateRangeInput(),fileInput(),numericInput(),passwordInput(),radioButtons(),selectInput(),sliderInput(),submitButton(),textAreaInput(),textInput(),varSelectInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  checkboxGroupInput("variable", "Variables to show:",                     c("Cylinders" = "cyl",                       "Transmission" = "am",                       "Gears" = "gear")),  tableOutput("data"))server <- function(input, output, session) {  output$data <- renderTable({    mtcars[, c("mpg", input$variable), drop = FALSE]  }, rownames = TRUE)}shinyApp(ui, server)ui <- fluidPage(  checkboxGroupInput("icons", "Choose icons:",    choiceNames =      list(icon("calendar"), icon("bed"),           icon("cog"), icon("bug")),    choiceValues =      list("calendar", "bed", "cog", "bug")  ),  textOutput("txt"))server <- function(input, output, session) {  output$txt <- renderText({    icons <- paste(input$icons, collapse = ", ")    paste("You chose", icons)  })}shinyApp(ui, server)}

Checkbox Input Control

Description

Create a checkbox that can be used to specify logical values.

Usage

checkboxInput(inputId, label, value = FALSE, width = NULL)

Arguments

inputId

Theinput slot that will be used to access the value.

label

Display label for the control, orNULL for no label.

value

Initial value (TRUE orFALSE).

width

The width of the input, e.g.'400px', or'100%';seevalidateCssUnit().

Value

A checkbox control that can be added to a UI definition.

Server value

TRUE if checked,FALSE otherwise.

See Also

checkboxGroupInput(),updateCheckboxInput()

Other input elements:actionButton(),checkboxGroupInput(),dateInput(),dateRangeInput(),fileInput(),numericInput(),passwordInput(),radioButtons(),selectInput(),sliderInput(),submitButton(),textAreaInput(),textInput(),varSelectInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  checkboxInput("somevalue", "Some value", FALSE),  verbatimTextOutput("value"))server <- function(input, output) {  output$value <- renderText({ input$somevalue })}shinyApp(ui, server)}

Control interactive plot point events

Description

These functions give control over theclick,dblClick andhover events generated byimageOutput() andplotOutput().

Usage

clickOpts(id, clip = TRUE)dblclickOpts(id, clip = TRUE, delay = 400)hoverOpts(  id,  delay = 300,  delayType = c("debounce", "throttle"),  clip = TRUE,  nullOutside = TRUE)

Arguments

id

Input value name. For example, if the value is"plot_click",then the event data will be available asinput$plot_click.

clip

Should the click area be clipped to the plotting area? IfFALSE, then the server will receive click events even when the mouse isoutside the plotting area, as long as it is still inside the image.

delay

FordblClickOpts(): the maximum delay (in ms) between apair clicks for them to be counted as a double-click.

ForhoverOpts(): how long to delay (in ms) when debouncing or throttlingbefore sending the mouse location to the server.

delayType

The type of algorithm for limiting the number of hoverevents. Use"throttle" to limit the number of hover events to oneeverydelay milliseconds. Use"debounce" to suspend eventswhile the cursor is moving, and wait until the cursor has been at rest fordelay milliseconds before sending an event.

nullOutside

IfTRUE (the default), the value will be set toNULL when the mouse exits the plotting area. IfFALSE, thevalue will stop changing when the cursor exits the plotting area.

See Also

brushOpts() for brushing events.


Create a column within a UI definition

Description

Create a column for use within afluidRow() orfixedRow()

Usage

column(width, ..., offset = 0)

Arguments

width

The grid width of the column (must be between 1 and 12)

...

Elements to include within the column

offset

The number of columns to offset this column from the end of theprevious column.

Value

A column that can be included within afluidRow() orfixedRow().

See Also

fluidRow(),fixedRow().

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  fluidRow(    column(4,      sliderInput("obs", "Number of observations:",                  min = 1, max = 1000, value = 500)    ),    column(8,      plotOutput("distPlot")    )  ))server <- function(input, output) {  output$distPlot <- renderPlot({    hist(rnorm(input$obs))  })}shinyApp(ui, server)ui <- fluidPage(  fluidRow(    column(width = 4,      "4"    ),    column(width = 3, offset = 2,      "3 offset 2"    )  ))shinyApp(ui, server = function(input, output) { })}

Conditional Panel

Description

Creates a panel that is visible or not, depending on the value of aJavaScript expression. The JS expression is evaluated once at startup andwhenever Shiny detects a relevant change in input/output.

Usage

conditionalPanel(condition, ..., ns = NS(NULL))

Arguments

condition

A JavaScript expression that will be evaluated repeatedly todetermine whether the panel should be displayed.

...

Elements to include in the panel.

ns

Thenamespace() object of the current module, ifany.

Details

In the JS expression, you can refer toinput andoutputJavaScript objects that contain the current values of input and output. Forexample, if you have an input with an id offoo, then you can useinput.foo to read its value. (Be sure not to modify the input/outputobjects, as this may cause unpredictable behavior.)

Note

You are not recommended to use special JavaScript characters such as aperiod. in the input id's, but if you do use them anyway, forexample,inputId = "foo.bar", you will have to useinput["foo.bar"] instead ofinput.foo.bar to read the inputvalue.

Examples

## Only run this example in interactive R sessionsif (interactive()) {  ui <- fluidPage(    sidebarPanel(      selectInput("plotType", "Plot Type",        c(Scatter = "scatter", Histogram = "hist")      ),      # Only show this panel if the plot type is a histogram      conditionalPanel(        condition = "input.plotType == 'hist'",        selectInput(          "breaks", "Breaks",          c("Sturges", "Scott", "Freedman-Diaconis", "[Custom]" = "custom")        ),        # Only show this panel if Custom is selected        conditionalPanel(          condition = "input.breaks == 'custom'",          sliderInput("breakCount", "Break Count", min = 1, max = 50, value = 10)        )      )    ),    mainPanel(      plotOutput("plot")    )  )  server <- function(input, output) {    x <- rnorm(100)    y <- rnorm(100)    output$plot <- renderPlot({      if (input$plotType == "scatter") {        plot(x, y)      } else {        breaks <- input$breaks        if (breaks == "custom") {          breaks <- input$breakCount        }        hist(x, breaks = breaks)      }    })  }  shinyApp(ui, server)}

Implement custom render functions

Description

Developer-facing utilities for implementing a customrenderXXX() function.Before using these utilities directly, consider using thehtmlwidgets package to implement customoutputs (i.e., customrenderXXX()/xxxOutput() functions). That said,these utilities can be used more directly if a full-blown htmlwidget isn'tneeded and/or the user-supplied reactive expression needs to be wrapped inadditional call(s).

Usage

createRenderFunction(  func,  transform = function(value, session, name, ...) value,  outputFunc = NULL,  outputArgs = NULL,  cacheHint = "auto",  cacheWriteHook = NULL,  cacheReadHook = NULL)quoToFunction(q, label = sys.call(-1)[[1]], ..stacktraceon = FALSE)installExprFunction(  expr,  name,  eval.env = parent.frame(2),  quoted = FALSE,  assign.env = parent.frame(1),  label = sys.call(-1)[[1]],  wrappedWithLabel = TRUE,  ..stacktraceon = FALSE)

Arguments

func

A function without parameters, that returns user data. If thereturned value is a promise, then the render function will proceed in asyncmode.

transform

A function that takes four arguments:value,session,name, and... (for future-proofing). Thisfunction will be invoked each time a value is returned fromfunc,and is responsible for changing the value into a JSON-ready value to beJSON-encoded and sent to the browser.

outputFunc

The UI function that is used (or most commonly used) withthis render function. This can be used in R Markdown documents to createcomplete output widgets out of just the render function.

outputArgs

A list of arguments to pass to theuiFunc. Renderfunctions should includeoutputArgs = list() in their own parameter list,and pass through the value tomarkRenderFunction, to allow app authors tocustomize outputs. (Currently, this is only supported for dynamicallygenerated UIs, such as those created by Shiny code snippets embedded in RMarkdown documents).

cacheHint

One of"auto",FALSE, or some other information toidentify this instance for caching usingbindCache(). If"auto", itwill try to automatically infer caching information. IfFALSE, do notallow caching for the object. Some render functions (such asrenderPlot)contain internal state that makes them unsuitable for caching.

cacheWriteHook

Used if the render function is passed tobindCache().This is an optional callback function to invoke before saving the valuefrom the render function to the cache. This function must accept oneargument, the value returned fromrenderFunc, and should return the valueto store in the cache.

cacheReadHook

Used if the render function is passed tobindCache().This is an optional callback function to invoke after reading a value fromthe cache (if there is a cache hit). The function will be passed oneargument, the value retrieved from the cache. This can be useful when someside effect needs to occur for a render function to behave correctly. Forexample, some render functions callcreateWebDependency() so that Shinyis able to serve JS and CSS resources.

q

Quosure of the expressionx. When capturing expressions to createyour quosure, it is recommended to userlang::enquo0() to not unquotethe object too early. Seerlang::enquo0() for more details.

label

A label for the object to be shown in the debugger. Defaults tothe name of the calling function.

expr

A quoted or unquoted expression, or a quosure.

name

The name the function should be given

eval.env

The desired environment for the function. Defaults to thecalling environment two steps back.

quoted

Is the expression quoted?

assign.env

The environment in which the function should be assigned.

wrappedWithLabel,..stacktraceon

Advanced use only. For stack manipulation purposes; seestacktrace().

Details

To implement a customrenderXXX() function, essentially 2 things are needed:

  1. Capture the user's reactive expression as a function.

    • NewrenderXXX() functions can usequoToFunction() for this, butalready existingrenderXXX() functions that containenv andquotedparameters may want to continue usinginstallExprFunction() for betterlegacy support (see examples).

  2. Flag the resulting function (from 1) as a Shiny rendering function andalso provide a UI container for displaying the result of the renderingfunction.

    • createRenderFunction() is currently recommended (instead ofmarkRenderFunction()) for this step (see examples).

Value

An annotated render function, ready to be assigned to anoutput slot.

Functions

Examples

# A custom render function that repeats the supplied value 3 timesrenderTriple <- function(expr) {  # Wrap user-supplied reactive expression into a function  func <- quoToFunction(rlang::enquo0(expr))  createRenderFunction(    func,    transform = function(value, session, name, ...) {      paste(rep(value, 3), collapse=", ")    },    outputFunc = textOutput  )}# For better legacy support, consider using installExprFunction() over quoToFunction()renderTripleLegacy <- function(expr, env = parent.frame(), quoted = FALSE) {  func <- installExprFunction(expr, "func", env, quoted)  createRenderFunction(    func,    transform = function(value, session, name, ...) {      paste(rep(value, 3), collapse=", ")    },    outputFunc = textOutput  )}# Test render function from the consolereactiveConsole(TRUE)v <- reactiveVal("basic")r <- renderTriple({ v() })r()#> [1] "basic, basic, basic"# User can supply quoted code via rlang::quo(). Note that evaluation of the# expression happens when r2() is invoked, not when r2 is created.q <- rlang::quo({ v() })r2 <- rlang::inject(renderTriple(!!q))v("rlang")r2()#> [1] "rlang, rlang, rlang"# Supplying quoted code without rlang::quo() requires installExprFunction()expr <- quote({ v() })r3 <- renderTripleLegacy(expr, quoted = TRUE)v("legacy")r3()#> [1] "legacy, legacy, legacy"# The legacy approach also supports with quosures (env is ignored in this case)q <- rlang::quo({ v() })r4 <- renderTripleLegacy(q, quoted = TRUE)v("legacy-rlang")r4()#> [1] "legacy-rlang, legacy-rlang, legacy-rlang"# Turn off reactivity in the consolereactiveConsole(FALSE)

Create a web dependency

Description

Ensure that a file-based HTML dependency (from the htmltools package) can beserved over Shiny's HTTP server. This function works by usingaddResourcePath() to map the HTML dependency's directory to aURL.

Usage

createWebDependency(dependency, scrubFile = TRUE)

Arguments

dependency

A single HTML dependency object, created usinghtmltools::htmlDependency(). If thesrc value is named,thenhref and/orfile names must be present.

scrubFile

If TRUE (the default), removesrc$file for thedependency. This prevents the local file path from being sent to the clientwhen dynamic web dependencies are used. If FALSE, don't removesrc$file. Setting it to FALSE should be needed only in very unusualcases.

Value

A single HTML dependency object that has anhref-named elementin itssrc.


Table output with the JavaScript DataTables library

Description

[Deprecated]

This function is deprecated, useDT::renderDT() instead. Itprovides a superset of functionality, better performance, and better userexperience.

Usage

dataTableOutput(outputId)renderDataTable(  expr,  options = NULL,  searchDelay = 500,  callback = "function(oTable) {}",  escape = TRUE,  env = parent.frame(),  quoted = FALSE,  outputArgs = list())

Arguments

outputId

output variable to read the table from

expr

An expression that returns a data frame or a matrix.

options

A list of initialization options to be passed to DataTables,or a function to return such a list. You can find a complete list ofoptions athttps://datatables.net/reference/option/.

Any top-level strings with class"AsIs" (as created byI()) will beevaluated in JavaScript. This is useful when the type of the option valueis not supported in JSON, e.g., a JavaScript function, which can beobtained by evaluating a character string. This only applies to theroot-level elements of options list, and does not worked for lower-levelelements in the list.

searchDelay

The delay for searching, in milliseconds (to avoid toofrequent search requests).

callback

A JavaScript function to be applied to the DataTable object.This is useful for DataTables plug-ins, which often require the DataTableinstance to be available.

escape

Whether to escape HTML entities in the table:TRUE meansto escape the whole table, andFALSE means not to escape it.Alternatively, you can specify numeric column indices or column names toindicate which columns to escape, e.g.1:5 (the first 5 columns),c(1, 3, 4), orc(-1, -3) (all columns except the first andthird), orc('Species', 'Sepal.Length').

env

The parent environment for the reactive expression. By default,this is the calling environment, the same as when defining an ordinarynon-reactive expression. Ifexpr is a quosure andquoted isTRUE,thenenv is ignored.

quoted

If it isTRUE, then thequote()ed value ofexprwill be used whenexpr is evaluated. Ifexpr is a quosure and youwould like to use its expression as a value forexpr, then you must setquoted toTRUE.

outputArgs

A list of arguments to be passed through to the implicitcall todataTableOutput() whenrenderDataTable() is usedin an interactive R Markdown document.

Examples

## Only run this example in interactive R sessionsif (interactive()) {  # pass a callback function to DataTables using I()  shinyApp(    ui = fluidPage(      fluidRow(        column(12,          dataTableOutput('table')        )      )    ),    server = function(input, output) {      output$table <- renderDataTable(iris,        options = list(          pageLength = 5,          initComplete = I("function(settings, json) {alert('Done.');}")        )      )    }  )}

Create date input

Description

Creates a text input which, when clicked on, brings up a calendar thatthe user can click on to select dates.

Usage

dateInput(  inputId,  label,  value = NULL,  min = NULL,  max = NULL,  format = "yyyy-mm-dd",  startview = "month",  weekstart = 0,  language = "en",  width = NULL,  autoclose = TRUE,  datesdisabled = NULL,  daysofweekdisabled = NULL)

Arguments

inputId

Theinput slot that will be used to access the value.

label

Display label for the control, orNULL for no label.

value

The starting date. Either a Date object, or a string inyyyy-mm-dd format. If NULL (the default), will use the current datein the client's time zone.

min

The minimum allowed date. Either a Date object, or a string inyyyy-mm-dd format.

max

The maximum allowed date. Either a Date object, or a string inyyyy-mm-dd format.

format

The format of the date to display in the browser. Defaults to"yyyy-mm-dd".

startview

The date range shown when the input object is first clicked.Can be "month" (the default), "year", or "decade".

weekstart

Which day is the start of the week. Should be an integerfrom 0 (Sunday) to 6 (Saturday).

language

The language used for month and day names. Default is "en".Other valid values include "ar", "az", "bg", "bs", "ca", "cs", "cy", "da","de", "el", "en-AU", "en-GB", "eo", "es", "et", "eu", "fa", "fi", "fo","fr-CH", "fr", "gl", "he", "hr", "hu", "hy", "id", "is", "it-CH", "it","ja", "ka", "kh", "kk", "ko", "kr", "lt", "lv", "me", "mk", "mn", "ms","nb", "nl-BE", "nl", "no", "pl", "pt-BR", "pt", "ro", "rs-latin", "rs","ru", "sk", "sl", "sq", "sr-latin", "sr", "sv", "sw", "th", "tr", "uk","vi", "zh-CN", and "zh-TW".

width

The width of the input, e.g.'400px', or'100%';seevalidateCssUnit().

autoclose

Whether or not to close the datepicker immediately when adate is selected.

datesdisabled

Which dates should be disabled. Either a Date object,or a string inyyyy-mm-dd format.

daysofweekdisabled

Days of the week that should be disabled. Should bea integer vector with values from 0 (Sunday) to 6 (Saturday).

Details

The dateformat string specifies how the date will be displayed inthe browser. It allows the following values:

Server value

ADate vector of length 1.

See Also

dateRangeInput(),updateDateInput()

Other input elements:actionButton(),checkboxGroupInput(),checkboxInput(),dateRangeInput(),fileInput(),numericInput(),passwordInput(),radioButtons(),selectInput(),sliderInput(),submitButton(),textAreaInput(),textInput(),varSelectInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  dateInput("date1", "Date:", value = "2012-02-29"),  # Default value is the date in client's time zone  dateInput("date2", "Date:"),  # value is always yyyy-mm-dd, even if the display format is different  dateInput("date3", "Date:", value = "2012-02-29", format = "mm/dd/yy"),  # Pass in a Date object  dateInput("date4", "Date:", value = Sys.Date()-10),  # Use different language and different first day of week  dateInput("date5", "Date:",          language = "ru",          weekstart = 1),  # Start with decade view instead of default month view  dateInput("date6", "Date:",            startview = "decade"),  # Disable Mondays and Tuesdays.  dateInput("date7", "Date:", daysofweekdisabled = c(1,2)),  # Disable specific dates.  dateInput("date8", "Date:", value = "2012-02-29",            datesdisabled = c("2012-03-01", "2012-03-02")))shinyApp(ui, server = function(input, output) { })}

Create date range input

Description

Creates a pair of text inputs which, when clicked on, bring up calendars thatthe user can click on to select dates.

Usage

dateRangeInput(  inputId,  label,  start = NULL,  end = NULL,  min = NULL,  max = NULL,  format = "yyyy-mm-dd",  startview = "month",  weekstart = 0,  language = "en",  separator = " to ",  width = NULL,  autoclose = TRUE)

Arguments

inputId

Theinput slot that will be used to access the value.

label

Display label for the control, orNULL for no label.

start

The initial start date. Either a Date object, or a string inyyyy-mm-dd format. If NULL (the default), will use the currentdate in the client's time zone.

end

The initial end date. Either a Date object, or a string inyyyy-mm-dd format. If NULL (the default), will use the currentdate in the client's time zone.

min

The minimum allowed date. Either a Date object, or a string inyyyy-mm-dd format.

max

The maximum allowed date. Either a Date object, or a string inyyyy-mm-dd format.

format

The format of the date to display in the browser. Defaults to"yyyy-mm-dd".

startview

The date range shown when the input object is first clicked.Can be "month" (the default), "year", or "decade".

weekstart

Which day is the start of the week. Should be an integerfrom 0 (Sunday) to 6 (Saturday).

language

The language used for month and day names. Default is "en".Other valid values include "ar", "az", "bg", "bs", "ca", "cs", "cy", "da","de", "el", "en-AU", "en-GB", "eo", "es", "et", "eu", "fa", "fi", "fo","fr-CH", "fr", "gl", "he", "hr", "hu", "hy", "id", "is", "it-CH", "it","ja", "ka", "kh", "kk", "ko", "kr", "lt", "lv", "me", "mk", "mn", "ms","nb", "nl-BE", "nl", "no", "pl", "pt-BR", "pt", "ro", "rs-latin", "rs","ru", "sk", "sl", "sq", "sr-latin", "sr", "sv", "sw", "th", "tr", "uk","vi", "zh-CN", and "zh-TW".

separator

String to display between the start and end input boxes.

width

The width of the input, e.g.'400px', or'100%';seevalidateCssUnit().

autoclose

Whether or not to close the datepicker immediately when adate is selected.

Details

The dateformat string specifies how the date will be displayed inthe browser. It allows the following values:

Server value

ADate vector of length 2.

See Also

dateInput(),updateDateRangeInput()

Other input elements:actionButton(),checkboxGroupInput(),checkboxInput(),dateInput(),fileInput(),numericInput(),passwordInput(),radioButtons(),selectInput(),sliderInput(),submitButton(),textAreaInput(),textInput(),varSelectInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  dateRangeInput("daterange1", "Date range:",                 start = "2001-01-01",                 end   = "2010-12-31"),  # Default start and end is the current date in the client's time zone  dateRangeInput("daterange2", "Date range:"),  # start and end are always specified in yyyy-mm-dd, even if the display  # format is different  dateRangeInput("daterange3", "Date range:",                 start  = "2001-01-01",                 end    = "2010-12-31",                 min    = "2001-01-01",                 max    = "2012-12-21",                 format = "mm/dd/yy",                 separator = " - "),  # Pass in Date objects  dateRangeInput("daterange4", "Date range:",                 start = Sys.Date()-10,                 end = Sys.Date()+10),  # Use different language and different first day of week  dateRangeInput("daterange5", "Date range:",                 language = "de",                 weekstart = 1),  # Start with decade view instead of default month view  dateRangeInput("daterange6", "Date range:",                 startview = "decade"))shinyApp(ui, server = function(input, output) { })}

Slow down a reactive expression with debounce/throttle

Description

Transforms a reactive expression by preventing its invalidation signals frombeing sent unnecessarily often. This lets you ignore a very "chatty" reactiveexpression until it becomes idle, which is useful when the intermediatevalues don't matter as much as the final value, and the downstreamcalculations that depend on the reactive expression take a long time.debounce andthrottle use different algorithms for slowing downinvalidation signals; see Details.

Usage

debounce(r, millis, priority = 100, domain = getDefaultReactiveDomain())throttle(r, millis, priority = 100, domain = getDefaultReactiveDomain())

Arguments

r

A reactive expression (that invalidates too often).

millis

The debounce/throttle time window. You may optionally pass ano-arg function or reactive expression instead, e.g. to let the end-usercontrol the time window.

priority

Debounce/throttle is implemented under the hood usingobservers. Use this parameter to set the priority ofthese observers. Generally, this should be higher than the priorities ofdownstream observers and outputs (which default to zero).

domain

Seedomains.

Details

This is not a true debounce/throttle in that it will not preventrfrom being called many times (in fact it may be called more times thanusual), but rather, the reactive invalidation signal that is produced byr is debounced/throttled instead. Therefore, these functions should beused whenr is cheap but the things it will trigger (downstreamoutputs and reactives) are expensive.

Debouncing means that every invalidation fromr will be held for thespecified time window. Ifr invalidates again within that time window,then the timer starts over again. This means that as long as invalidationscontinually arrive fromr within the time window, the debouncedreactive will not invalidate at all. Only after the invalidations stop (orslow down sufficiently) will the downstream invalidation be sent.

⁠ooo-oo-oo---- => -----------o-⁠

(In this graphical depiction, each character represents a unit of time, andthe time window is 3 characters.)

Throttling, on the other hand, delays invalidation if thethrottledreactive recently (within the time window) invalidated. Newrinvalidations do not reset the time window. This means that if invalidationscontinually come fromr within the time window, the throttled reactivewill invalidate regularly, at a rate equal to or slower than the timewindow.

⁠ooo-oo-oo---- => o--o--o--o---⁠

Limitations

Because R is single threaded, we can't come close to guaranteeing that thetiming of debounce/throttle (or any other timing-related functions inShiny) will be consistent or accurate; at the time we want to emit aninvalidation signal, R may be performing a different task and we have noway to interrupt it (nor would we necessarily want to if we could).Therefore, it's best to think of the time windows you pass to thesefunctions as minimums.

You may also see undesirable behavior if the amount of time spent doingdownstream processing for each change approaches or exceeds the timewindow: in this case, debounce/throttle may not have any effect, as thetime each subsequent event is considered is already after the time windowhas expired.

Examples

## Only run examples in interactive R sessionsif (interactive()) {options(device.ask.default = FALSE)library(shiny)library(magrittr)ui <- fluidPage(  plotOutput("plot", click = clickOpts("hover")),  helpText("Quickly click on the plot above, while watching the result table below:"),  tableOutput("result"))server <- function(input, output, session) {  hover <- reactive({    if (is.null(input$hover))      list(x = NA, y = NA)    else      input$hover  })  hover_d <- hover %>% debounce(1000)  hover_t <- hover %>% throttle(1000)  output$plot <- renderPlot({    plot(cars)  })  output$result <- renderTable({    data.frame(      mode = c("raw", "throttle", "debounce"),      x = c(hover()$x, hover_t()$x, hover_d()$x),      y = c(hover()$y, hover_t()$y, hover_d()$y)    )  })}shinyApp(ui, server)}

Shiny Developer Mode

Description

[Experimental]

Developer Mode enables a number ofoptions() to make a developer's lifeeasier, like enabling non-minified JS and printing messages aboutdeprecated functions and options.

Shiny Developer Mode can be enabled by callingdevmode(TRUE) and disabledby callingdevmode(FALSE).

Please see the function descriptions for more details.

Usage

devmode(  devmode = getOption("shiny.devmode", TRUE),  verbose = getOption("shiny.devmode.verbose", TRUE))in_devmode()with_devmode(devmode, code, verbose = getOption("shiny.devmode.verbose", TRUE))devmode_inform(  message,  .frequency = "regularly",  .frequency_id = message,  .file = stderr(),  ...)register_devmode_option(name, devmode_message = NULL, devmode_default = NULL)get_devmode_option(  name,  default = NULL,  devmode_default = missing_arg(),  devmode_message = missing_arg())

Arguments

devmode

Logical value which should be set toTRUE to enable ShinyDeveloper Mode

verbose

Logical value which should be set toTRUE display ShinyDeveloper messages

code

Code to execute with the temporary Dev Mode options set

message

Developer Mode message to be sent torlang::inform()

.frequency

Frequency of the Developer Mode message used withrlang::inform(). Defaults to once every 8 hours.

.frequency_id

rlang::inform() message identifier. Defaults tomessage.

.file

Output connection forrlang::inform(). Defaults tostderr()

...

Parameters passed torlang::inform()

name

Name of option to look for inoptions()

devmode_message

Message to display once every 8 hours when utilizingthedevmode_default value. Ifdevmode_message is missing, theregistereddevmode_message value be used.

devmode_default

Default value to return ifin_devmode() returnsTRUE and the specified option is not set inoptions(). Forget_devmode_option(), ifdevmode_default is missing, theregistereddevmode_default value will be used.

default

Default value to return ifin_devmode() returnsTRUE and the specified option is not set inoptions().

Functions

Avoiding direct dependency on shiny

The methods explained in this help file act independently from the rest ofShiny but are included to provide blue prints for your own packages. Ifyour package already has (or is willing to take) a dependency on Shiny, werecommend using the exported Shiny methods for consistent behavior. Notethat if you use exported Shiny methods, it will cause the Shiny package toload. This may be undesirable if your code will be used in (for example) RMarkdown documents that do not have a Shiny runtime (runtime: shiny).

If your package cannot take a dependency on Shiny, we recommendingre-implementing these two functions:

  1. in_devmode():

    This function should returnTRUE ifgetOption("shiny.devmode") is set.In addition, we strongly recommend that it also checks to make suretestthat is not testing.

    in_devmode <- function() {  isTRUE(getOption("shiny.devmode", FALSE)) &&    !identical(Sys.getenv("TESTTHAT"), "true")}
  2. get_devmode_option(name, default, devmode_default, devmode_message):

    This function is similar togetOption(name, default), but when the optionis not set, the default value changes depending on the Dev Mode.get_devmode_option() should be implemented as follows:

    • If not in Dev Mode:

      • ReturngetOption(name, default).

    • If in Dev Mode:

      • Get the global optiongetOption(name) value.

      • If the global option value is set:

        • Return the value.

      • If the global option value is not set:

        • Notify the developer that the Dev Mode default value will be used.

        • Return the Dev Mode default value.

    When notifying the developer that the default value has changed, we stronglyrecommend displaying a message (devmode_message) tostderr() once every 8hours usingrlang::inform(). This will keep the author up to date as towhich Dev Mode options are being altered. To allow developers a chance todisable Dev Mode messages, the message should be skipped ifgetOption("shiny.devmode.verbose", TRUE) is notTRUE.

    get_devmode_option <- function(name, default = NULL, devmode_default, devmode_message) {  if (!in_devmode()) {    # Dev Mode disabled, act like `getOption()`    return(getOption(name, default = default))  }  # Dev Mode enabled, update the default value for `getOption()`  getOption(name, default = {    # Notify developer    if (      !missing(devmode_message) &&      !is.null(devmode_message) &&      getOption("shiny.devmode.verbose", TRUE)    ) {      rlang::inform(        message = devmode_message,        .frequency = "regularly",        .frequency_id = devmode_message,        .file = stderr()      )    }    # Return Dev Mode default value `devmode_default`    devmode_default  })}

The remaining functions in this file are used for author convenience and arenot recommended for all reimplementation situations.

Examples

# Enable Shiny Developer modedevmode()in_devmode() # TRUE/FALSE?# Execute code in a temporary shiny dev modewith_devmode(TRUE, in_devmode()) # TRUE# Ex: Within shiny, we register the option "shiny.minified"#   to default to `FALSE` when in Dev Mode## Not run: register_devmode_option(  "shiny.minified",  devmode_message = paste0(    "Using full shiny javascript file. ",    "To use the minified version, call `options(shiny.minified = TRUE)`"  ),  devmode_default = FALSE)## End(Not run)# Used within `shiny::runApp(launch.browser)`get_devmode_option("shiny.minified", TRUE) # TRUE if Dev mode is offis_minified <- with_devmode(TRUE, {  get_devmode_option("shiny.minified", TRUE)})is_minified # FALSE

Create disk cache (deprecated)

Description

Create disk cache (deprecated)

Usage

diskCache(  dir = NULL,  max_size = 500 * 1024^2,  max_age = Inf,  max_n = Inf,  evict = c("lru", "fifo"),  destroy_on_finalize = FALSE,  missing = key_missing(),  exec_missing = deprecated(),  logfile = NULL)

Arguments

dir

Directory to store files for the cache. IfNULL (the default) itwill create and use a temporary directory.

max_size

Maximum size of the cache, in bytes. If the cache exceedsthis size, cached objects will be removed according to the value of theevict. UseInf for no size limit. The default is 1 gigabyte.

max_age

Maximum age of files in cache before they are evicted, inseconds. UseInf for no age limit.

max_n

Maximum number of objects in the cache. If the number of objectsexceeds this value, then cached objects will be removed according to thevalue ofevict. UseInf for no limit of number of items.

evict

The eviction policy to use to decide which objects are removedwhen a cache pruning occurs. Currently,"lru" and"fifo" are supported.

destroy_on_finalize

IfTRUE, then when the cache_disk object isgarbage collected, the cache directory and all objects inside of it will bedeleted from disk. IfFALSE (the default), it will do nothing whenfinalized.

missing

A value to return whenget(key) is called but the key is notpresent in the cache. The default is akey_missing() object. It isactually an expression that is evaluated each time there is a cache miss.See section Missing keys for more information.

exec_missing

Deprecated.

logfile

An optional filename or connection object to where logginginformation will be written. To log to the console, usestderr() orstdout().


Reactive domains

Description

Reactive domains are a mechanism for establishing ownership over reactiveprimitives (like reactive expressions and observers), even if the set ofreactive primitives is dynamically created. This is useful for lifetimemanagement (i.e. destroying observers when the Shiny session that createdthem ends) and error handling.

Usage

getDefaultReactiveDomain()withReactiveDomain(domain, expr)onReactiveDomainEnded(domain, callback, failIfNull = FALSE)

Arguments

domain

A valid domain object (for example, a Shiny session), orNULL

expr

An expression to evaluate underdomain

callback

A callback function to be invoked

failIfNull

IfTRUE then an error is given if thedomainisNULL

Details

At any given time, there can be either a single "default" reactive domainobject, or none (i.e. the reactive domain object isNULL). You canaccess the current default reactive domain by callinggetDefaultReactiveDomain.

Unless you specify otherwise, newly created observers and reactiveexpressions will be assigned to the current default domain (if any). You canoverride this assignment by providing an explicitdomain argument toreactive() orobserve().

For advanced usage, it's possible to override the default domain usingwithReactiveDomain. Thedomain argument will be made thedefault domain whileexpr is evaluated.

Implementers of new reactive primitives can useonReactiveDomainEndedas a convenience function for registering callbacks. If the reactive domainisNULL andfailIfNull isFALSE, then the callback willnever be invoked.


Create a download button or link

Description

Use these functions to create a download button or link; when clicked, itwill initiate a browser download. The filename and contents are specified bythe correspondingdownloadHandler() defined in the serverfunction.

Usage

downloadButton(  outputId,  label = "Download",  class = NULL,  ...,  icon = shiny::icon("download"))downloadLink(outputId, label = "Download", class = NULL, ...)

Arguments

outputId

The name of the output slot that thedownloadHandleris assigned to.

label

The label that should appear on the button.

class

Additional CSS classes to apply to the tag, if any.

...

Other arguments to pass to the container tag function.

icon

Anicon() to appear on the button. Default isicon("download").

See Also

downloadHandler()

Examples

## Not run: ui <- fluidPage(  p("Choose a dataset to download."),  selectInput("dataset", "Dataset", choices = c("mtcars", "airquality")),  downloadButton("downloadData", "Download"))server <- function(input, output) {  # The requested dataset  data <- reactive({    get(input$dataset)  })  output$downloadData <- downloadHandler(    filename = function() {      # Use the selected dataset as the suggested file name      paste0(input$dataset, ".csv")    },    content = function(file) {      # Write the dataset to the `file` that will be downloaded      write.csv(data(), file)    }  )}shinyApp(ui, server)## End(Not run)

File Downloads

Description

Allows content from the Shiny application to be made available to the user asfile downloads (for example, downloading the currently visible data as a CSVfile). Both filename and contents can be calculated dynamically at the timethe user initiates the download. Assign the return value to a slot onoutput in your server function, and in the UI usedownloadButton() ordownloadLink() to make thedownload available.

Usage

downloadHandler(filename, content, contentType = NULL, outputArgs = list())

Arguments

filename

A string of the filename, including extension, that theuser's web browser should default to when downloading the file; or afunction that returns such a string. (Reactive values and functions may beused from this function.)

content

A function that takes a single argumentfile that is afile path (string) of a nonexistent temp file, and writes the content tothat file path. (Reactive values and functions may be used from thisfunction.)

contentType

A string of the download'scontent type, forexample"text/csv" or"image/png". IfNULL, the content typewill be guessed based on the filename extension, orapplication/octet-stream if the extension is unknown.

outputArgs

A list of arguments to be passed through to the implicitcall todownloadButton() whendownloadHandler is usedin an interactive R Markdown document.

See Also

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  downloadButton("downloadData", "Download"))server <- function(input, output) {  # Our dataset  data <- mtcars  output$downloadData <- downloadHandler(    filename = function() {      paste("data-", Sys.Date(), ".csv", sep="")    },    content = function(file) {      write.csv(data, file)    }  )}shinyApp(ui, server)}

Enable bookmarking for a Shiny application

Description

There are two types of bookmarking: saving an application's state to disk onthe server, and encoding the application's state in a URL. For state that hasbeen saved to disk, the state can be restored with the corresponding stateID. For URL-encoded state, the state of the application is encoded in theURL, and no server-side storage is needed.

URL-encoded bookmarking is appropriate for applications where there not manyinput values that need to be recorded. Some browsers have a length limit forURLs of about 2000 characters, and if there are many inputs, the length ofthe URL can exceed that limit.

Saved-on-server bookmarking is appropriate when there are many inputs, orwhen the bookmarked state requires storing files.

Usage

enableBookmarking(store = c("url", "server", "disable"))

Arguments

store

Either"url", which encodes all of the relevant values ina URL,"server", which saves to disk on the server, or"disable", which disables any previously-enabled bookmarking.

Details

For restoring state to work properly, the UI must be a function that takesone argument,request. In most Shiny applications, the UI is not afunction; it might have the formfluidPage(....). Converting it to afunction is as simple as wrapping it in a function, as infunction(request) { fluidPage(....) }.

By default, all input values will be bookmarked, except for the values ofpasswordInputs. fileInputs will be saved if the state is saved on a server,but not if the state is encoded in a URL.

When bookmarking state, arbitrary values can be stored, by passing a functionas theonBookmark argument. That function will be passed aShinySaveState object. Thevalues field of the object is a listwhich can be manipulated to save extra information. Additionally, if thestate is being saved on the server, and thedir field of that objectcan be used to save extra information to files in that directory.

For saved-to-server state, this is how the state directory is chosen:

When used withshinyApp(), this function must be called beforeshinyApp(), or in theshinyApp()'sonStart function. Analternative to calling theenableBookmarking() function is to use theenableBookmarkingargument forshinyApp(). See examplesbelow.

See Also

onBookmark(),onBookmarked(),onRestore(), andonRestored() for registeringcallback functions that are invoked when the state is bookmarked orrestored.

Also seeupdateQueryString().

Examples

## Only run these examples in interactive R sessionsif (interactive()) {# Basic example with state encoded in URLui <- function(request) {  fluidPage(    textInput("txt", "Text"),    checkboxInput("chk", "Checkbox"),    bookmarkButton()  )}server <- function(input, output, session) { }enableBookmarking("url")shinyApp(ui, server)# An alternative to calling enableBookmarking(): use shinyApp's# enableBookmarking argumentshinyApp(ui, server, enableBookmarking = "url")# Same basic example with state saved to diskenableBookmarking("server")shinyApp(ui, server)# Save/restore arbitrary valuesui <- function(req) {  fluidPage(    textInput("txt", "Text"),    checkboxInput("chk", "Checkbox"),    bookmarkButton(),    br(),    textOutput("lastSaved")  )}server <- function(input, output, session) {  vals <- reactiveValues(savedTime = NULL)  output$lastSaved <- renderText({    if (!is.null(vals$savedTime))      paste("Last saved at", vals$savedTime)    else      ""  })  onBookmark(function(state) {    vals$savedTime <- Sys.time()    # state is a mutable reference object, and we can add arbitrary values    # to it.    state$values$time <- vals$savedTime  })  onRestore(function(state) {    vals$savedTime <- state$values$time  })}enableBookmarking(store = "url")shinyApp(ui, server)# Usable with dynamic UI (set the slider, then change the text input,# click the bookmark button)ui <- function(request) {  fluidPage(    sliderInput("slider", "Slider", 1, 100, 50),    uiOutput("ui"),    bookmarkButton()  )}server <- function(input, output, session) {  output$ui <- renderUI({    textInput("txt", "Text", input$slider)  })}enableBookmarking("url")shinyApp(ui, server)# Exclude specific inputs (The only input that will be saved in this# example is chk)ui <- function(request) {  fluidPage(    passwordInput("pw", "Password"), # Passwords are never saved    sliderInput("slider", "Slider", 1, 100, 50), # Manually excluded below    checkboxInput("chk", "Checkbox"),    bookmarkButton()  )}server <- function(input, output, session) {  setBookmarkExclude("slider")}enableBookmarking("url")shinyApp(ui, server)# Update the browser's location bar every time an input changes. This should# not be used with enableBookmarking("server"), because that would create a# new saved state on disk every time the user changes an input.ui <- function(req) {  fluidPage(    textInput("txt", "Text"),    checkboxInput("chk", "Checkbox")  )}server <- function(input, output, session) {  observe({    # Trigger this observer every time an input changes    reactiveValuesToList(input)    session$doBookmark()  })  onBookmarked(function(url) {    updateQueryString(url)  })}enableBookmarking("url")shinyApp(ui, server)# Save/restore uploaded filesui <- function(request) {  fluidPage(    sidebarLayout(      sidebarPanel(        fileInput("file1", "Choose CSV File", multiple = TRUE,          accept = c(            "text/csv",            "text/comma-separated-values,text/plain",            ".csv"          )        ),        tags$hr(),        checkboxInput("header", "Header", TRUE),        bookmarkButton()      ),      mainPanel(        tableOutput("contents")      )    )  )}server <- function(input, output) {  output$contents <- renderTable({    inFile <- input$file1    if (is.null(inFile))      return(NULL)    if (nrow(inFile) == 1) {      read.csv(inFile$datapath, header = input$header)    } else {      data.frame(x = "multiple files")    }  })}enableBookmarking("server")shinyApp(ui, server)}

Register expressions for export in test mode

Description

This function registers expressions that will be evaluated when a test exportevent occurs. These events are triggered by accessing a snapshot URL.

Usage

exportTestValues(  ...,  quoted_ = FALSE,  env_ = parent.frame(),  session_ = getDefaultReactiveDomain())

Arguments

...

Named arguments that are quoted or unquoted expressions that willbe captured and evaluated when snapshot URL is visited.

quoted_

Are the expression quoted? Default isFALSE.

env_

The environment in which the expression should be evaluated.

session_

A Shiny session object.

Details

This function only has an effect if the app is launched in test mode. This isdone by callingrunApp() withtest.mode=TRUE, or by setting theglobal optionshiny.testmode toTRUE.

Examples

## Only run this example in interactive R sessionsif (interactive()) {options(shiny.testmode = TRUE)# This application shows the test snapshot URL; clicking on it will# fetch the input, output, and exported values in JSON format.shinyApp(  ui = basicPage(    h4("Snapshot URL: "),    uiOutput("url"),    h4("Current values:"),    verbatimTextOutput("values"),    actionButton("inc", "Increment x")  ),  server = function(input, output, session) {    vals <- reactiveValues(x = 1)    y <- reactive({ vals$x + 1 })    observeEvent(input$inc, {      vals$x <<- vals$x + 1    })    exportTestValues(      x = vals$x,      y = y()    )    output$url <- renderUI({      url <- session$getTestSnapshotUrl(format="json")      a(href = url, url)    })    output$values <- renderText({      paste0("vals$x: ", vals$x, "\ny: ", y())    })  })}

Convert an expression to a function

Description

[Superseded] Please useinstallExprFunction() for a betterdebugging experience (Shiny 0.8.0). If theexpr andquoted parameters are not needed, please seequoToFunction() (Shiny 1.6.0).

Usage

exprToFunction(expr, env = parent.frame(), quoted = FALSE)

Arguments

expr

A quoted or unquoted expression, or a quosure.

env

The desired environment for the function. Defaults to thecalling environment two steps back.

quoted

Is the expression quoted?

Details

Similar toinstallExprFunction() but doesn't register debug hooks.

See Also

installExprFunction() for the modern approach to converting an expression to a function


File Upload Control

Description

Create a file upload control that can be used to upload one or more files.

Usage

fileInput(  inputId,  label,  multiple = FALSE,  accept = NULL,  width = NULL,  buttonLabel = "Browse...",  placeholder = "No file selected",  capture = NULL)

Arguments

inputId

Theinput slot that will be used to access the value.

label

Display label for the control, orNULL for no label.

multiple

Whether the user should be allowed to select and uploadmultiple files at once.Does not work on older browsers, includingInternet Explorer 9 and earlier.

accept

A character vector of "unique file type specifiers" which givesthe browser a hint as to the type of file the server expects. Many browsersuse this prevent the user from selecting an invalid file.

A unique file type specifier can be:

  • A case insensitive extension like.csv or.rds.

  • A valid MIME type, liketext/plain orapplication/pdf

  • One of⁠audio/*⁠,⁠video/*⁠, or⁠image/*⁠ meaning any audio, video,or image type, respectively.

width

The width of the input, e.g.'400px', or'100%';seevalidateCssUnit().

buttonLabel

The label used on the button. Can be text or an HTML tagobject.

placeholder

The text to show before a file has been uploaded.

capture

What source to use for capturing image, audio or video data.This attribute facilitates user access to a device's media capturemechanism, such as a camera, or microphone, from within a file uploadcontrol.

A value ofuser indicates that the user-facing camera and/or microphoneshould be used. A value ofenvironment specifies that the outward-facingcamera and/or microphone should be used.

By default on most phones, this will accept still photos or video. Forstill photos only, also useaccept="image/*". For video only, useaccept="video/*".

Details

Whenever a file upload completes, the corresponding input variable is set toa dataframe. See the⁠Server value⁠ section.

Each time files are uploaded, they are written to a new random subdirectoryinside of R's process-level temporary directory. The Shiny user session keepstrack of all uploads in the session, and when the session ends, Shiny deletesall of the subdirectories where files where uploaded to.

Server value

Adata.frame that contains one row for each selected file, and followingcolumns:

name

The filename provided by the web browser. This isnot the path to read to get at the actual data that was uploaded(seedatapath column).

size

The size of the uploaded data, inbytes.

type

The MIME type reported by the browser (for example,text/plain), or empty string if the browser didn't know.

datapath

The path to a temp file that contains the data that wasuploaded. This file may be deleted if the user performs another uploadoperation.

See Also

Other input elements:actionButton(),checkboxGroupInput(),checkboxInput(),dateInput(),dateRangeInput(),numericInput(),passwordInput(),radioButtons(),selectInput(),sliderInput(),submitButton(),textAreaInput(),textInput(),varSelectInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  sidebarLayout(    sidebarPanel(      fileInput("file1", "Choose CSV File", accept = ".csv"),      checkboxInput("header", "Header", TRUE)    ),    mainPanel(      tableOutput("contents")    )  ))server <- function(input, output) {  output$contents <- renderTable({    file <- input$file1    ext <- tools::file_ext(file$datapath)    req(file)    validate(need(ext == "csv", "Please upload a csv file"))    read.csv(file$datapath, header = input$header)  })}shinyApp(ui, server)}

Create a page that fills the window

Description

fillPage creates a page whose height and width always fill theavailable area of the browser window.

Usage

fillPage(  ...,  padding = 0,  title = NULL,  bootstrap = TRUE,  theme = NULL,  lang = NULL)

Arguments

...

Elements to include within the page.

padding

Padding to use for the body. This can be a numeric vector(which will be interpreted as pixels) or a character vector with valid CSSlengths. The length can be between one and four. If one, then that valuewill be used for all four sides. If two, then the first value will be usedfor the top and bottom, while the second value will be used for left andright. If three, then the first will be used for top, the second will beleft and right, and the third will be bottom. If four, then the values willbe interpreted as top, right, bottom, and left respectively.

title

The title to use for the browser window/tab (it will not beshown in the document).

bootstrap

IfTRUE, load the Bootstrap CSS library.

theme

One of the following:

  • NULL (the default), which implies a "stock" build of Bootstrap 3.

  • Abslib::bs_theme() object. This can be used to replace a stockbuild of Bootstrap 3 with a customized version of Bootstrap 3 or higher.

  • A character string pointing to an alternative Bootstrap stylesheet(normally a css file within the www directory, e.g.www/bootstrap.css).

lang

ISO 639-1 language code for the HTML page, such as "en" or "ko".This will be used as the lang in the<html> tag, as in<html lang="en">.The default (NULL) results in an empty string.

Details

ThefluidPage() andfixedPage() functions are usedfor creating web pages that are laid out from the top down, leavingwhitespace at the bottom if the page content's height is smaller than thebrowser window, and scrolling if the content is larger than the window.

fillPage is designed to latch the document body's size to the size ofthe window. This makes it possible to fill it with content that also scalesto the size of the window.

For example,fluidPage(plotOutput("plot", height = "100%")) will notwork as expected; the plot element's effective height will be0,because the plot's containing elements (⁠<div>⁠ and⁠<body>⁠) haveautomatic height; that is, they determine their own height based onthe height of their contained elements. However,fillPage(plotOutput("plot", height = "100%")) will work becausefillPage fixes the⁠<body>⁠ height at 100% of the window height.

Note thatfillPage(plotOutput("plot")) will not cause the plot to fillthe page. Like most Shiny output widgets,plotOutput's default heightis a fixed number of pixels. You must explicitly setheight = "100%"if you want a plot (or htmlwidget, say) to fill its container.

One must be careful what layouts/panels/elements come between thefillPage and the plots/widgets. Any container that has an automaticheight will cause children withheight = "100%" to misbehave. Stickto functions that are designed for fill layouts, such as the ones in thispackage.

See Also

Other layout functions:fixedPage(),flowLayout(),fluidPage(),navbarPage(),sidebarLayout(),splitLayout(),verticalLayout()

Examples

fillPage(  tags$style(type = "text/css",    ".half-fill { width: 50%; height: 100%; }",    "#one { float: left; background-color: #ddddff; }",    "#two { float: right; background-color: #ccffcc; }"  ),  div(id = "one", class = "half-fill",    "Left half"  ),  div(id = "two", class = "half-fill",    "Right half"  ),  padding = 10)fillPage(  fillRow(    div(style = "background-color: red; width: 100%; height: 100%;"),    div(style = "background-color: blue; width: 100%; height: 100%;")  ))

Flex Box-based row/column layouts

Description

Creates row and column layouts with proportionally-sized cells, using theFlex Box layout model of CSS3. These can be nested to create arbitraryproportional-grid layouts.Warning: Flex Box is not well supportedby Internet Explorer, so these functions should only be used where modernbrowsers can be assumed.

Usage

fillRow(..., flex = 1, width = "100%", height = "100%")fillCol(..., flex = 1, width = "100%", height = "100%")

Arguments

...

UI objects to put in each row/column cell; each argument willoccupy a single cell. (To put multiple items in a single cell, you can usetagList() ordiv() to combine them.) Namedarguments will be used as attributes on thediv element thatencapsulates the row/column.

flex

Determines how space should be distributed to the cells. Can be asingle value like1 or2 to evenly distribute the availablespace; or use a vector of numbers to specify the proportions. For example,flex = c(2, 3) would cause the space to be split 40%/60% betweentwo cells. NA values will cause the corresponding cell to be sizedaccording to its contents (without growing or shrinking).

width,height

The total amount of width and height to use for theentire row/column. For the default height of"100%" to beeffective, the parent must befillPage, anotherfillRow/fillCol, or some other HTML element whose height isnot determined by the height of its contents.

Details

If you try to usefillRow andfillCol inside of otherShiny containers, such assidebarLayout(),navbarPage(), or eventags$div, you will probably findthat they will not appear. This is due tofillRow andfillColdefaulting toheight="100%", which will only work inside ofcontainers that have determined their own size (rather than shrinking tothe size of their contents, as is usually the case in HTML).

To avoid this problem, you have two options:

Examples

# Only run this example in interactive R sessions.if (interactive()) {ui <- fillPage(fillRow(  plotOutput("plotLeft", height = "100%"),  fillCol(    plotOutput("plotTopRight", height = "100%"),    plotOutput("plotBottomRight", height = "100%")  )))server <- function(input, output, session) {  output$plotLeft <- renderPlot(plot(cars))  output$plotTopRight <- renderPlot(plot(pressure))  output$plotBottomRight <- renderPlot(plot(AirPassengers))}shinyApp(ui, server)}

Create a page with a fixed layout

Description

Functions for creating fixed page layouts. A fixed page layout consists ofrows which in turn include columns. Rows exist for the purpose of making suretheir elements appear on the same line (if the browser has adequate width).Columns exist for the purpose of defining how much horizontal space within a12-unit wide grid it's elements should occupy. Fixed pages limit their widthto 940 pixels on a typical display, and 724px or 1170px on smaller and largerdisplays respectively.

Usage

fixedPage(..., title = NULL, theme = NULL, lang = NULL)fixedRow(...)

Arguments

...

Elements to include within the container

title

The browser window title (defaults to the host URL of the page)

theme

One of the following:

  • NULL (the default), which implies a "stock" build of Bootstrap 3.

  • Abslib::bs_theme() object. This can be used to replace a stockbuild of Bootstrap 3 with a customized version of Bootstrap 3 or higher.

  • A character string pointing to an alternative Bootstrap stylesheet(normally a css file within the www directory, e.g.www/bootstrap.css).

lang

ISO 639-1 language code for the HTML page, such as "en" or "ko".This will be used as the lang in the<html> tag, as in<html lang="en">.The default (NULL) results in an empty string.

Details

To create a fixed page use thefixedPage function and includeinstances offixedRow andcolumn() within it. Note thatunlikefluidPage(), fixed pages cannot make use of higher-levellayout functions likesidebarLayout, rather, all layout must be donewithfixedRow andcolumn.

Value

A UI definition that can be passed to theshinyUI function.

Note

See the Shiny Application Layout Guide for additional details on laying out fixedpages.

See Also

column()

Other layout functions:fillPage(),flowLayout(),fluidPage(),navbarPage(),sidebarLayout(),splitLayout(),verticalLayout()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fixedPage(  title = "Hello, Shiny!",  fixedRow(    column(width = 4,      "4"    ),    column(width = 3, offset = 2,      "3 offset 2"    )  ))shinyApp(ui, server = function(input, output) { })}

Flow layout

Description

Lays out elements in a left-to-right, top-to-bottom arrangement. The elementson a given row will be top-aligned with each other. This layout will not workwell with elements that have a percentage-based width (e.g.plotOutput() at its default setting ofwidth = "100%").

Usage

flowLayout(..., cellArgs = list())

Arguments

...

Unnamed arguments will become child elements of the layout. Namedarguments will become HTML attributes on the outermost tag.

cellArgs

Any additional attributes that should be used for each cellof the layout.

See Also

Other layout functions:fillPage(),fixedPage(),fluidPage(),navbarPage(),sidebarLayout(),splitLayout(),verticalLayout()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- flowLayout(  numericInput("rows", "How many rows?", 5),  selectInput("letter", "Which letter?", LETTERS),  sliderInput("value", "What value?", 0, 100, 50))shinyApp(ui, server = function(input, output) { })}

Create a page with fluid layout

Description

Functions for creating fluid page layouts. A fluid page layout consists ofrows which in turn include columns. Rows exist for the purpose of making suretheir elements appear on the same line (if the browser has adequate width).Columns exist for the purpose of defining how much horizontal space within a12-unit wide grid it's elements should occupy. Fluid pages scale theircomponents in realtime to fill all available browser width.

Usage

fluidPage(..., title = NULL, theme = NULL, lang = NULL)fluidRow(...)

Arguments

...

Elements to include within the page

title

The browser window title (defaults to the host URL of the page).Can also be set as a side effect of thetitlePanel() function.

theme

One of the following:

  • NULL (the default), which implies a "stock" build of Bootstrap 3.

  • Abslib::bs_theme() object. This can be used to replace a stockbuild of Bootstrap 3 with a customized version of Bootstrap 3 or higher.

  • A character string pointing to an alternative Bootstrap stylesheet(normally a css file within the www directory, e.g.www/bootstrap.css).

lang

ISO 639-1 language code for the HTML page, such as "en" or "ko".This will be used as the lang in the<html> tag, as in<html lang="en">.The default (NULL) results in an empty string.

Details

To create a fluid page use thefluidPage function and includeinstances offluidRow andcolumn() within it. As analternative to low-level row and column functions you can also usehigher-level layout functions likesidebarLayout().

Value

A UI definition that can be passed to theshinyUI function.

Note

See the Shiny-Application-Layout-Guide for additional details on laying out fluidpages.

See Also

column()

Other layout functions:fillPage(),fixedPage(),flowLayout(),navbarPage(),sidebarLayout(),splitLayout(),verticalLayout()

Examples

## Only run examples in interactive R sessionsif (interactive()) {# Example of UI with fluidPageui <- fluidPage(  # Application title  titlePanel("Hello Shiny!"),  sidebarLayout(    # Sidebar with a slider input    sidebarPanel(      sliderInput("obs",                  "Number of observations:",                  min = 0,                  max = 1000,                  value = 500)    ),    # Show a plot of the generated distribution    mainPanel(      plotOutput("distPlot")    )  ))# Server logicserver <- function(input, output) {  output$distPlot <- renderPlot({    hist(rnorm(input$obs))  })}# Complete app with UI and server componentsshinyApp(ui, server)# UI demonstrating column layoutsui <- fluidPage(  title = "Hello Shiny!",  fluidRow(    column(width = 4,      "4"    ),    column(width = 3, offset = 2,      "3 offset 2"    )  ))shinyApp(ui, server = function(input, output) { })}

Freeze a reactive value

Description

These functions freeze areactiveVal(), or an element of areactiveValues(). If the value is accessed while frozen, a"silent" exception is raised and the operation is stopped. This is the samething that happens ifreq(FALSE) is called. The value is thawed(un-frozen; accessing it will no longer raise an exception) when the currentreactive domain is flushed. In a Shiny application, this occurs after all ofthe observers are executed.NOTE: We are considering deprecatingfreezeReactiveVal, andfreezeReactiveValue except whenx isinput.If this affects your app, please let us know by leaving a comment onthis GitHub issue.

Usage

freezeReactiveVal(x)freezeReactiveValue(x, name)

Arguments

x

ForfreezeReactiveValue, areactiveValues()object (likeinput); forfreezeReactiveVal, areactiveVal() object.

name

The name of a value in thereactiveValues() object.

See Also

req()

Examples

## Only run this examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  selectInput("data", "Data Set", c("mtcars", "pressure")),  checkboxGroupInput("cols", "Columns (select 2)", character(0)),  plotOutput("plot"))server <- function(input, output, session) {  observe({    data <- get(input$data)    # Sets a flag on input$cols to essentially do req(FALSE) if input$cols    # is accessed. Without this, an error will momentarily show whenever a    # new data set is selected.    freezeReactiveValue(input, "cols")    updateCheckboxGroupInput(session, "cols", choices = names(data))  })  output$plot <- renderPlot({    # When a new data set is selected, input$cols will have been invalidated    # above, and this will essentially do the same as req(FALSE), causing    # this observer to stop and raise a silent exception.    cols <- input$cols    data <- get(input$data)    if (length(cols) == 2) {      plot(data[[ cols[1] ]], data[[ cols[2] ]])    }  })}shinyApp(ui, server)}

Get output information

Description

Returns information about the currently executing output, including itsname (i.e.,outputId);and in some cases, relevant sizing and styling information.

Usage

getCurrentOutputInfo(session = getDefaultReactiveDomain())

Arguments

session

The current Shiny session.

Value

NULL if called outside of an output context; otherwise,a list which includes:

Examples

if (interactive()) {  shinyApp(    fluidPage(      tags$style(HTML("body {background-color: black; color: white; }")),      tags$style(HTML("body a {color: purple}")),      tags$style(HTML("#info {background-color: teal; color: orange; }")),      plotOutput("p"),      "Computed CSS styles for the output named info:",      tagAppendAttributes(        textOutput("info"),        class = "shiny-report-theme"      )    ),    function(input, output) {      output$p <- renderPlot({        info <- getCurrentOutputInfo()        par(bg = info$bg(), fg = info$fg(), col.axis = info$fg(), col.main = info$fg())        plot(1:10, col = info$accent(), pch = 19)        title("A simple R plot that uses its CSS styling")      })      output$info <- renderText({        info <- getCurrentOutputInfo()        jsonlite::toJSON(          list(            bg = info$bg(),            fg = info$fg(),            accent = info$accent(),            font = info$font()          ),          auto_unbox = TRUE        )      })    }  )}

Obtain Shiny's Bootstrap Sass theme

Description

Intended for use by Shiny developers to create Shiny bindings with intelligentstyling based on thebootstrapLib()'stheme value.

Usage

getCurrentTheme()

Value

If called at render-time (i.e., inside ahtmltools::tagFunction()),andbootstrapLib()'stheme has been set to abslib::bs_theme()object, then this returns thetheme. Otherwise, this returnsNULL.

See Also

getCurrentOutputInfo(),bootstrapLib(),htmltools::tagFunction()


Get the query string / hash component from the URL

Description

Two user friendly wrappers for getting the query string and the hashcomponent from the app's URL.

Usage

getQueryString(session = getDefaultReactiveDomain())getUrlHash(session = getDefaultReactiveDomain())

Arguments

session

A Shiny session object.

Details

These can be particularly useful if you want to display different contentdepending on the values in the query string / hash (e.g. instead of basingthe conditional on an input or a calculated reactive, you can base it on thequery string). However, note that, if you're changing the query string / hashprogrammatically from within the server code, you must use⁠updateQueryString(_yourNewQueryString_, mode = "push")⁠. The defaultmode forupdateQueryString is"replace", which doesn'traise any events, so any observers or reactives that depend on it willnot get triggered. However, if you're changing the query string / hashdirectly by typing directly in the browser and hitting enter, you don't haveto worry about this.

Value

ForgetQueryString, a named list. For example, the querystring?param1=value1&param2=value2 becomeslist(param1 = value1, param2 = value2). ForgetUrlHash, a character vector withthe hash (including the leading⁠#⁠ symbol).

See Also

updateQueryString()

Examples

## Only run this example in interactive R sessionsif (interactive()) {  ## App 1: getQueryString  ## Printing the value of the query string  ## (Use the back and forward buttons to see how the browser  ## keeps a record of each state)  shinyApp(    ui = fluidPage(      textInput("txt", "Enter new query string"),      helpText("Format: ?param1=val1&param2=val2"),      actionButton("go", "Update"),      hr(),      verbatimTextOutput("query")    ),    server = function(input, output, session) {      observeEvent(input$go, {        updateQueryString(input$txt, mode = "push")      })      output$query <- renderText({        query <- getQueryString()        queryText <- paste(names(query), query,                       sep = "=", collapse=", ")        paste("Your query string is:\n", queryText)      })    }  )  ## App 2: getUrlHash  ## Printing the value of the URL hash  ## (Use the back and forward buttons to see how the browser  ## keeps a record of each state)  shinyApp(    ui = fluidPage(      textInput("txt", "Enter new hash"),      helpText("Format: #hash"),      actionButton("go", "Update"),      hr(),      verbatimTextOutput("hash")    ),    server = function(input, output, session) {      observeEvent(input$go, {        updateQueryString(input$txt, mode = "push")      })      output$hash <- renderText({        hash <- getUrlHash()        paste("Your hash is:\n", hash)      })    }  )}

Get or set Shiny options

Description

There are two mechanisms for working with options for Shiny. One is theoptions() function, which is part of base R, and the other is theshinyOptions() function, which is in the Shiny package. The reason forthese two mechanisms is has to do with legacy code and scoping.

Theoptions() function sets options globally, for the duration of the Rprocess. ThegetOption() function retrieves the value of an option. Allshiny related options of this type are prefixed with"shiny.".

TheshinyOptions() function sets the value of a shiny option, but unlikeoptions(), it is not always global in scope; the options may be scopedglobally, to an application, or to a user session in an application,depending on the context. ThegetShinyOption() function retrieves a valueof a shiny option. Currently, the options set viashinyOptions are forinternal use only.

Usage

getShinyOption(name, default = NULL)shinyOptions(...)

Arguments

name

Name of an option to get.

default

Value to be returned if the option is not currently set.

...

Options to set, with the formname = value.

Options withoptions()

shiny.autoreload (defaults toFALSE)

IfTRUE when a Shiny app is launched, theapp directory will be continually monitored for changes to files thathave the extensions: r, htm, html, js, css, png, jpg, jpeg, gif. If anychanges are detected, all connected Shiny sessions are reloaded. Thisallows for fast feedback loops when tweaking Shiny UI.

Monitoring for changes is no longer expensive, thanks to thewatcherpackage, but this feature is still intended only for development.

You can customize the file patterns Shiny will monitor by setting theshiny.autoreload.pattern option. For example, to monitor onlyui.R:options(shiny.autoreload.pattern = glob2rx("ui.R")).

As mentioned above, Shiny no longer polls watched files for changes.Instead, usingwatcher, Shiny is notified of file changes as theyoccur. These changes are batched together within a customizable latencyperiod. You can adjust this period by settingoptions(shiny.autoreload.interval = 2000) (in milliseconds). This valueconverted to seconds and passed to thelatency argument ofwatcher::watcher(). The default latency is 250ms.

shiny.deprecation.messages (defaults toTRUE)

This controls whether messages fordeprecated functions in Shiny will be printed. SeeshinyDeprecated() for more information.

shiny.error (defaults toNULL)

This can be a function which is called when an erroroccurs. For example,options(shiny.error=recover) will result athe debugger prompt when an error occurs.

shiny.fullstacktrace (defaults toFALSE)

Controls whether "pretty" (FALSE) or fullstack traces (TRUE) are dumped to the console when errors occur during Shiny app execution.Pretty stack traces attempt to only show user-supplied code, but this pruning can't alwaysbe done 100% correctly.

shiny.host (defaults to"127.0.0.1")

The IP address that Shiny should listen on. SeerunApp() for more information.

shiny.jquery.version (defaults to3)

The major version of jQuery to use.Currently only values of3 or1 are supported. If1, then jQuery 1.12.4 is used. If3,then jQuery 3.7.1 is used.

shiny.json.digits (defaults toI(16))

Max number of digits to use when convertingnumbers to JSON format to send to the client web browser. UseI() to specify significant digits.UseNA for max precision.

shiny.launch.browser (defaults tointeractive())

A boolean which controls the default behaviorwhen an app is run. SeerunApp() for more information.

shiny.mathjax.url (defaults to"https://mathjax.rstudio.com/latest/MathJax.js")

The URL that should be used to load MathJax, viawithMathJax().

shiny.mathjax.config (defaults to"config=TeX-AMS-MML_HTMLorMML")

The querystringused to load MathJax, viawithMathJax().

shiny.maxRequestSize (defaults to 5MB)

This is a number which specifies the maximumweb request size, which serves as a size limit for file uploads.

shiny.minified (defaults toTRUE)

By defaultWhether or not to include Shiny's JavaScript as a minified (shiny.min.js)or un-minified (shiny.js) file. The un-minified version is larger,but can be helpful for development and debugging.

shiny.port (defaults to a random open port)

A port number that Shiny will listen on. SeerunApp() for more information.

shiny.reactlog (defaults toFALSE)

IfTRUE, enable logging of reactive events,which can be viewed later with thereactlogShow() function.This incurs a substantial performance penalty and should not be used inproduction.

shiny.sanitize.errors (defaults toFALSE)

IfTRUE, then normal errors (i.e.errors not wrapped insafeError) won't show up in the app; a simplegeneric error message is printed instead (the error and stack trace printedto the console remain unchanged). If you want to sanitize errors in general, but you DO want aparticular errore to get displayed to the user, then set this optiontoTRUE and usestop(safeError(e)) for errors you want theuser to see.

shiny.stacktraceoffset (defaults toTRUE)

IfTRUE, then Shiny's printed stacktraces will display srcrefs one line above their usual location. This isan arguably more intuitive arrangement for casual R users, as the nameof a function appears next to the srcref where it is defined, rather thanwhere it is currently being called from.

shiny.suppressMissingContextError (defaults toFALSE)

Normally, invoking a reactiveoutside of a reactive context (orisolate()) results inan error. If this isTRUE, don't error in these cases. Thisshould only be used for debugging or demonstrations of reactivity at theconsole.

shiny.testmode (defaults toFALSE)

IfTRUE, then various features for testing Shinyapplications are enabled.

shiny.snapshotsortc (defaults toFALSE)

IfTRUE, test snapshot keysforshinytest will be sorted consistently using the C locale. Snapshotsretrieved byshinytest2 will always sort using the C locale.

shiny.trace (defaults toFALSE)

Print messages sent between the R server and the webbrowser client to the R console. This is useful for debugging. Possiblevalues are"send" (only print messages sent to the client),"recv" (only print messages received by the server),TRUE(print all messages), orFALSE (default; don't print any of thesemessages).

shiny.autoload.r (defaults toTRUE)

IfTRUE, then the R/of a shiny app will automatically be sourced.

shiny.useragg (defaults toTRUE)

Set toFALSE to prevent PNG rendering via theragg package. SeeplotPNG() for more information.

shiny.usecairo (defaults toTRUE)

Set toFALSE to prevent PNG rendering via theCairo package. SeeplotPNG() for more information.

shiny.devmode (defaults toNULL)

Option to enable Shiny Developer Mode. When set,different defaultgetOption(key) values will be returned. Seedevmode() for more details.

shiny.otel.collect (defaults toSys.getenv("SHINY_OTEL_COLLECT", "all"))

Determines how Shiny will interact with OpenTelemetry.

Supported values:

  • "none" - No Shiny OpenTelemetry tracing.

  • "session" - Adds session start/end spans.

  • "reactive_update" - Spans for any synchronous/asynchronous reactiveupdate. (Includes"session" features).

  • "reactivity" - Spans for all reactive expressions and logs for settingreactive vals and values. (Includes"reactive_update" features). Thisoption must be set when creating any reactive objects that should recordOpenTelemetry spans / logs. SeewithOtelCollect() andlocalOtelCollect() for ways to set this option locally when creatingyour reactive expressions.

  • "all" - All Shiny OpenTelemetry tracing. Currently equivalent to"reactivity".

This option is useful for debugging and profiling while in production. Thisoption will only be useful if theotelsdk package is installed andotel::is_tracing_enabled() returnsTRUE. Please have any OpenTelemetryenvironment variables set before loading any relevant R packages.

To set this option locally within a specific part of your Shinyapplication, seewithOtelCollect() andlocalOtelCollect().

shiny.otel.sanitize.errors (defaults toTRUE)

IfTRUE, fatal and unhandled errors will be sanitized before being sent to the OpenTelemetry backend. The default value ofTRUE is set to avoid potentially sending sensitive information to the OpenTelemetry backend. If you want the full error message and stack trace to be sent to the OpenTelemetry backend, set this option toFALSE or usesafeError(e).

Scoping forshinyOptions()

There are three levels of scoping forshinyOptions(): global,application, and session.

The global option set is available by default. Any calls toshinyOptions() andgetShinyOption() outside of an app will access theglobal option set.

When a Shiny application is run withrunApp(), the global option set isduplicated and the new option set is available at the application level. Ifoptions are set fromglobal.R,app.R,ui.R, orserver.R (butoutside of the server function), then the application-level options will bemodified.

Each time a user session is started, the application-level option set isduplicated, for that session. If the options are set from inside the serverfunction, then they will be scoped to the session.

Options withshinyOptions()

There are a number of global options that affect Shiny's behavior. Thesecan be set globally withoptions() or locally (for a single app) withshinyOptions().

cache

A caching object that will be used byrenderCachedPlot(). If not specified, acachem::cache_mem() will beused.


Create a header panel

Description

DEPRECATED: usetitlePanel() instead.

Usage

headerPanel(title, windowTitle = title)

Arguments

title

An application title to display

windowTitle

The title that should be displayed by the browser window.Useful iftitle is not a string.

Value

A headerPanel that can be passed topageWithSidebar


Create a help text element

Description

Create help text which can be added to an input form to provide additionalexplanation or context.

Usage

helpText(...)

Arguments

...

One or more help text strings (or other inline HTML elements)

Value

A help text element that can be added to a UI definition.

Examples

helpText("Note: while the data view will show only",         "the specified number of observations, the",         "summary will be based on the full dataset.")

Create an HTML output element

Description

Render a reactive output variable as HTML within an application page. Thetext will be included within an HTMLdiv tag, and is presumed to containHTML content which should not be escaped.

Usage

htmlOutput(  outputId,  inline = FALSE,  container = if (inline) span else div,  fill = FALSE,  ...)uiOutput(  outputId,  inline = FALSE,  container = if (inline) span else div,  fill = FALSE,  ...)

Arguments

outputId

output variable to read the value from

inline

use an inline (span()) or block container (div())for the output

container

a function to generate an HTML element to contain the text

fill

IfTRUE, the result ofcontainer is treated asboth a fillitem and container (seehtmltools::bindFillRole()), which means both thecontainer as well as its immediate children (i.e., the result ofrenderUI()) are allowed to grow/shrink to fit a fill container with anopinionated height. Setfill = "item" orfill = "container" to treatcontainer as just a fill item or a fill container.

...

Other arguments to pass to the container tag function. This isuseful for providing additional classes for the tag.

Details

uiOutput is intended to be used withrenderUI on the server side. It iscurrently just an alias forhtmlOutput.

Value

An HTML output element that can be included in a panel

Examples

htmlOutput("summary")# Using a custom container and classtags$ul(  htmlOutput("summary", container = tags$li, class = "custom-li-output"))

Create an HTTP response object

Description

Create an HTTP response object

Usage

httpResponse(  status = 200L,  content_type = "text/html; charset=UTF-8",  content = "",  headers = list())

Arguments

status

HTTP status code for the response.

content_type

The value for theContent-Type header.

content

The body of the response, given as a single-element charactervector (will be encoded as UTF-8) or a raw vector.

headers

A named list of additional headers to include. Do not includeContent-Length (as it is automatically calculated) orContent-Type (thecontent_type argument is used instead).

Examples

httpResponse(status = 405L,  content_type = "text/plain",  content = "The requested method was not allowed")

Create an icon

Description

Create an icon for use within a page. Icons can appear on their own, insideof a button, and/or used withtabPanel() andnavbarMenu().

Usage

icon(name, class = NULL, lib = "font-awesome", ...)

Arguments

name

The name of the icon. A name from eitherFont Awesome (whenlib="font-awesome") orBootstrap Glyphicons (whenlib="glyphicon") may be provided. Note that the"fa-" and"glyphicon-" prefixes should not appear in name (i.e., the"fa-calendar" icon should be referred to as"calendar"). Aname ofNULL may also be provided to get a raw⁠<i>⁠ tag with no library attachedto it.

class

Additional classes to customize the style of an icon (see theusage examples for details onsupported styles).

lib

The icon library to use. Either"font-awesome" or"glyphicon".

...

Arguments passed to the⁠<i>⁠ tag ofhtmltools::tags.

Value

An⁠<i>⁠ (icon) HTML tag.

See Also

For lists of available icons, seehttps://fontawesome.com/iconsandhttps://getbootstrap.com/docs/3.3/components/#glyphicons

Examples

# add an icon to a submit buttonsubmitButton("Update View", icon = icon("redo"))navbarPage("App Title",  tabPanel("Plot", icon = icon("bar-chart-o")),  tabPanel("Summary", icon = icon("list-alt")),  tabPanel("Table", icon = icon("table")))

Input panel

Description

AflowLayout() with a grey border and light grey background,suitable for wrapping inputs.

Usage

inputPanel(...)

Arguments

...

Input controls or other HTML elements.


Dynamically insert/remove a tabPanel

Description

Dynamically insert or remove atabPanel() (or anavbarMenu()) from an existingtabsetPanel(),navlistPanel() ornavbarPage().

Usage

insertTab(  inputId,  tab,  target = NULL,  position = c("after", "before"),  select = FALSE,  session = getDefaultReactiveDomain())prependTab(  inputId,  tab,  select = FALSE,  menuName = NULL,  session = getDefaultReactiveDomain())appendTab(  inputId,  tab,  select = FALSE,  menuName = NULL,  session = getDefaultReactiveDomain())removeTab(inputId, target, session = getDefaultReactiveDomain())

Arguments

inputId

Theid of thetabsetPanel (ornavlistPanel ornavbarPage) into whichtab willbe inserted/removed.

tab

The item to be added (must be created withtabPanel,or withnavbarMenu).

target

If inserting: thevalue of an existingtabPanel, next to whichtab will be added.If removing: thevalue of thetabPanel thatyou want to remove. See Details if you want to insert next to/removean entirenavbarMenu instead.

position

Shouldtab be added before or after thetarget tab?

select

Shouldtab be selected upon being inserted?

session

The shiny session within which to call this function.

menuName

This argument should only be used when you want toprepend (or append)tab to the beginning (or end) of anexistingnavbarMenu() (which must itself be part ofan existingnavbarPage()). In this case, this argumentshould be themenuName that you gave yournavbarMenuwhen you first created it (by default, this is equal to the valueof thetitle argument). Note that you still need to set theinputId argument to whatever theid of the parentnavbarPage is. IfmenuName is left asNULL,tab will be prepended (or appended) to whateverinputId is.

Details

When you want to insert a new tab before or after an existing tab, youshould useinsertTab. When you want to prepend a tab (i.e. add atab to the beginning of thetabsetPanel), useprependTab.When you want to append a tab (i.e. add a tab to the end of thetabsetPanel), useappendTab.

FornavbarPage, you can insert/remove conventionaltabPanels (whether at the top level or nested inside anavbarMenu), as well as an entirenavbarMenu().For the latter case,target should be themenuName thatyou gave yournavbarMenu when you first created it (by default,this is equal to the value of thetitle argument).

See Also

showTab()

Examples

## Only run this example in interactive R sessionsif (interactive()) {# example app for inserting/removing a tabui <- fluidPage(  sidebarLayout(    sidebarPanel(      actionButton("add", "Add 'Dynamic' tab"),      actionButton("remove", "Remove 'Foo' tab")    ),    mainPanel(      tabsetPanel(id = "tabs",        tabPanel("Hello", "This is the hello tab"),        tabPanel("Foo", "This is the foo tab"),        tabPanel("Bar", "This is the bar tab")      )    )  ))server <- function(input, output, session) {  observeEvent(input$add, {    insertTab(inputId = "tabs",      tabPanel("Dynamic", "This a dynamically-added tab"),      target = "Bar"    )  })  observeEvent(input$remove, {    removeTab(inputId = "tabs", target = "Foo")  })}shinyApp(ui, server)# example app for prepending/appending a navbarMenuui <- navbarPage("Navbar page", id = "tabs",  tabPanel("Home",    actionButton("prepend", "Prepend a navbarMenu"),    actionButton("append", "Append a navbarMenu")  ))server <- function(input, output, session) {  observeEvent(input$prepend, {    id <- paste0("Dropdown", input$prepend, "p")    prependTab(inputId = "tabs",      navbarMenu(id,        tabPanel("Drop1", paste("Drop1 page from", id)),        tabPanel("Drop2", paste("Drop2 page from", id)),        "------",        "Header",        tabPanel("Drop3", paste("Drop3 page from", id))      )    )  })  observeEvent(input$append, {    id <- paste0("Dropdown", input$append, "a")    appendTab(inputId = "tabs",      navbarMenu(id,        tabPanel("Drop1", paste("Drop1 page from", id)),        tabPanel("Drop2", paste("Drop2 page from", id)),        "------",        "Header",        tabPanel("Drop3", paste("Drop3 page from", id))      )    )  })}shinyApp(ui, server)}

Insert and remove UI objects

Description

These functions allow you to dynamically add and remove arbitrary UIinto your app, whenever you want, as many times as you want.UnlikerenderUI(), the UI generated withinsertUI() is persistent:once it's created, it stays there until removed byremoveUI(). Eachnew call toinsertUI() creates more UI objects, in addition tothe ones already there (all independent from one another). Toupdate a part of the UI (ex: an input object), you must use theappropriaterender function or a customizedreactivefunction.

Usage

insertUI(  selector,  where = c("beforeBegin", "afterBegin", "beforeEnd", "afterEnd"),  ui,  multiple = FALSE,  immediate = FALSE,  session = getDefaultReactiveDomain())removeUI(  selector,  multiple = FALSE,  immediate = FALSE,  session = getDefaultReactiveDomain())

Arguments

selector

A string that is accepted by jQuery's selector(i.e. the strings to be placed in a⁠$(s)⁠ jQuery call).

ForinsertUI() this determines the element(s) relative to which youwant to insert your UI object. ForremoveUI() this determine theelement(s) to be removed. If you want to remove a Shiny input or output,note that many of these are wrapped in⁠<div>⁠s, so you may need to use asomewhat complex selector — see the Examples below. (Alternatively, youcould also wrap the inputs/outputs that you want to be able to removeeasily in a⁠<div>⁠ with an id.)

where

Where your UI object should go relative to the selector:

beforeBegin

Before the selector element itself

afterBegin

Just inside the selector element, before itsfirst child

beforeEnd

Just inside the selector element, after itslast child (default)

afterEnd

After the selector element itself

Adapted fromhttps://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML.

ui

The UI object you want to insert. This can be anything thatyou usually put inside your apps'sui function. If you're insertingmultiple elements in one call, make sure to wrap them in either atagList() or atags$div() (the latter option has theadvantage that you can give it anid to make it easier toreference or remove it later on). If you want to insert raw html, useui = HTML().

multiple

In case your selector matches more than one element,multiple determines whether Shiny should insert the UI objectrelative to all matched elements or just relative to the firstmatched element (default).

immediate

Whether the UI object should be immediately insertedor removed, or whether Shiny should wait until all outputs have beenupdated and all observers have been run (default).

session

The shiny session. Advanced use only.

Details

It's particularly useful to pairremoveUI withinsertUI(), but there isno restriction on what you can use it on. Any element that can be selectedthrough a jQuery selector can be removed through this function.

Examples

## Only run this example in interactive R sessionsif (interactive()) {# Define UIui <- fluidPage(  actionButton("add", "Add UI"))# Server logicserver <- function(input, output, session) {  observeEvent(input$add, {    insertUI(      selector = "#add",      where = "afterEnd",      ui = textInput(paste0("txt", input$add),                     "Insert some text")    )  })}# Complete app with UI and server componentsshinyApp(ui, server)}if (interactive()) {# Define UIui <- fluidPage(  actionButton("rmv", "Remove UI"),  textInput("txt", "This is no longer useful"))# Server logicserver <- function(input, output, session) {  observeEvent(input$rmv, {    removeUI(      selector = "div:has(> #txt)"    )  })}# Complete app with UI and server componentsshinyApp(ui, server)}

Scheduled Invalidation

Description

Schedules the current reactive context to be invalidated in the given numberof milliseconds.

Usage

invalidateLater(millis, session = getDefaultReactiveDomain())

Arguments

millis

Approximate milliseconds to wait before invalidating thecurrent reactive context.

session

A session object. This is needed to cancel any scheduledinvalidations after a user has ended the session. IfNULL, thenthis invalidation will not be tied to any session, and so it will stilloccur.

Details

If this is placed within an observer or reactive expression, that object willbe invalidated (and re-execute) after the interval has passed. There-execution will reset the invalidation flag, so in a typical use case, theobject will keep re-executing and waiting for the specified interval. It'spossible to stop this cycle by adding conditional logic that prevents theinvalidateLater from being run.

See Also

reactiveTimer() is a slightly less safe alternative.

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  sliderInput("n", "Number of observations", 2, 1000, 500),  plotOutput("plot"))server <- function(input, output, session) {  observe({    # Re-execute this reactive expression after 1000 milliseconds    invalidateLater(1000, session)    # Do something each time this is invalidated.    # The isolate() makes this observer _not_ get invalidated and re-executed    # when input$n changes.    print(paste("The value of input$n is", isolate(input$n)))  })  # Generate a new histogram at timed intervals, but not when  # input$n changes.  output$plot <- renderPlot({    # Re-execute this reactive expression after 2000 milliseconds    invalidateLater(2000)    hist(rnorm(isolate(input$n)))  })}shinyApp(ui, server)}

Checks whether an object is a reactivevalues object

Description

Checks whether its argument is a reactivevalues object.

Usage

is.reactivevalues(x)

Arguments

x

The object to test.

See Also

reactiveValues().


Check whether a Shiny application is running

Description

This function tests whether a Shiny application is currently running.

Usage

isRunning()

Value

TRUE if a Shiny application is currently running. Otherwise,FALSE.


Truthy and falsy values

Description

The terms "truthy" and "falsy" generally indicate whether a value, whencoerced to abase::logical(), isTRUE orFALSE. We usethe term a little loosely here; our usage tries to match the intuitivenotions of "Is this value missing or available?", or "Has the user providedan answer?", or in the case of action buttons, "Has the button beenclicked?".

Usage

isTruthy(x)

Arguments

x

An expression whose truthiness value we want to determine

Details

For example, atextInput that has not been filled out by the user hasa value of"", so that is considered a falsy value.

To be precise, a value is truthyunless it is one of:

Note in particular that the value0 is considered truthy, even thoughas.logical(0) isFALSE.


Create a non-reactive scope for an expression

Description

Executes the given expression in a scope where reactive values or expressioncan be read, but they cannot cause the reactive scope of the caller to bere-evaluated when they change.

Usage

isolate(expr)

Arguments

expr

An expression that can access reactive values or expressions.

Details

Ordinarily, the simple act of reading a reactive value causes a relationshipto be established between the caller and the reactive value, where a changeto the reactive value will cause the caller to re-execute. (The same appliesfor the act of getting a reactive expression's value.) Theisolatefunction lets you read a reactive value or expression without establishing thisrelationship.

The expression given toisolate() is evaluated in the callingenvironment. This means that if you assign a variable inside theisolate(), its value will be visible outside of theisolate().If you want to avoid this, you can usebase::local() inside theisolate().

This function can also be useful for calling reactive expression at theconsole, which can be useful for debugging. To do so, simply wrap thecalls to the reactive expression withisolate().

Examples

## Not run: observe({  input$saveButton  # Do take a dependency on input$saveButton  # isolate a simple expression  data <- get(isolate(input$dataset))  # No dependency on input$dataset  writeToDatabase(data)})observe({  input$saveButton  # Do take a dependency on input$saveButton  # isolate a whole block  data <- isolate({    a <- input$valueA   # No dependency on input$valueA or input$valueB    b <- input$valueB    c(a=a, b=b)  })  writeToDatabase(data)})observe({  x <- 1  # x outside of isolate() is affected  isolate(x <- 2)  print(x) # 2  y <- 1  # Use local() to avoid affecting calling environment  isolate(local(y <- 2))  print(y) # 1})## End(Not run)# Can also use isolate to call reactive expressions from the R consolevalues <- reactiveValues(A=1)fun <- reactive({ as.character(values$A) })isolate(fun())# "1"# isolate also works if the reactive expression accesses values from the# input object, like input$x

Knitr S3 methods

Description

These S3 methods are necessary to help Shiny applications and UI chunks embedthemselves in knitr/rmarkdown documents.

Usage

knit_print.shiny.appobj(x, ...)knit_print.shiny.render.function(x, ..., inline = FALSE)knit_print.reactive(x, ..., inline = FALSE)

Arguments

x

Object to knit_print

...

Additional knit_print arguments

inline

Whether the object is printed inline.


Load an app's supporting R files

Description

Loads all of the supporting R files of a Shiny application. Specifically,this function loads any top-level supporting.R files in the⁠R/⁠ directoryadjacent to theapp.R/server.R/ui.R files.

Usage

loadSupport(  appDir = NULL,  renv = new.env(parent = globalenv()),  globalrenv = globalenv())

Arguments

appDir

The application directory. IfappDir isNULL ornot supplied, the nearest enclosing directory that is a Shiny app, startingwith the current directory, is used.

renv

The environment in which the files in the⁠R/⁠ directory shouldbe evaluated.

globalrenv

The environment in whichglobal.R should be evaluated. IfNULL,global.R will not be evaluated at all.

Details

Since Shiny 1.5.0, this function is called by default when running anapplication. If it causes problems, there are two ways to opt out. You caneither place a file named⁠_disable_autoload.R⁠ in your R/ directory, orsetoptions(shiny.autoload.r=FALSE). If you set this option, it willaffect any application that runs later in the same R session, potentiallybreaking it, so after running your application, you should unset option withoptions(shiny.autoload.r=NULL)

The files are sourced in alphabetical order (as determined bylist.files).global.R is evaluated before the supporting R files in the⁠R/⁠ directory.


Make a reactive variable

Description

Turns a normal variable into a reactive variable, that is, one that hasreactive semantics when assigned or read in the usual ways. The variable mayalready exist; if so, its value will be used as the initial value of thereactive variable (orNULL if the variable did not exist).

Usage

makeReactiveBinding(symbol, env = parent.frame())

Arguments

symbol

Name of variable to make reactive, as a string.

env

Environment in which to create binding. Expert use only.

Value

None.

Examples

reactiveConsole(TRUE)a <- 10makeReactiveBinding("a")b <- reactive(a * -1)observe(print(b()))a <- 20a <- 30reactiveConsole(FALSE)

Mark a render function with attributes that will be used by the output

Description

Mark a render function with attributes that will be used by the output

Usage

markOutputAttrs(renderFunc, snapshotExclude = NULL, snapshotPreprocess = NULL)

Arguments

renderFunc

A function that is suitable for assigning to a Shiny outputslot.

snapshotExclude

If TRUE, exclude the output from test snapshots.

snapshotPreprocess

A function for preprocessing the value beforetaking a test snapshot.


Mark a function as a render function

Description

[Superseded] Please usecreateRenderFunction() tosupport async execution. (Shiny 1.1.0)

Usage

markRenderFunction(  uiFunc,  renderFunc,  outputArgs = list(),  cacheHint = "auto",  cacheWriteHook = NULL,  cacheReadHook = NULL)

Arguments

uiFunc

A function that renders Shiny UI. Must take a single argument:an output ID.

renderFunc

A function that is suitable for assigning to a Shiny outputslot.

outputArgs

A list of arguments to pass to theuiFunc. Renderfunctions should includeoutputArgs = list() in their own parameter list,and pass through the value tomarkRenderFunction, to allow app authors tocustomize outputs. (Currently, this is only supported for dynamicallygenerated UIs, such as those created by Shiny code snippets embedded in RMarkdown documents).

cacheHint

One of"auto",FALSE, or some other information toidentify this instance for caching usingbindCache(). If"auto", itwill try to automatically infer caching information. IfFALSE, do notallow caching for the object. Some render functions (such asrenderPlot)contain internal state that makes them unsuitable for caching.

cacheWriteHook

Used if the render function is passed tobindCache().This is an optional callback function to invoke before saving the valuefrom the render function to the cache. This function must accept oneargument, the value returned fromrenderFunc, and should return the valueto store in the cache.

cacheReadHook

Used if the render function is passed tobindCache().This is an optional callback function to invoke after reading a value fromthe cache (if there is a cache hit). The function will be passed oneargument, the value retrieved from the cache. This can be useful when someside effect needs to occur for a render function to behave correctly. Forexample, some render functions callcreateWebDependency() so that Shinyis able to serve JS and CSS resources.

Details

Should be called by implementers ofrenderXXX functions in order to marktheir return values as Shiny render functions, and to provide a hint to Shinyregarding what UI function is most commonly used with this type of renderfunction. This can be used in R Markdown documents to create complete outputwidgets out of just the render function.

Note that it is generally preferable to usecreateRenderFunction() insteadofmarkRenderFunction(). It essentially wraps up the user-providedexpression in thetransform function passed to it, then passes the resultingfunction tomarkRenderFunction(). It also provides a simpler callinginterface. There may be cases wheremarkRenderFunction() must be used instead ofcreateRenderFunction() – for example, when thetransform parameter ofcreateRenderFunction() is not flexible enough for your needs.

Value

TherenderFunc function, with annotations.

See Also

createRenderFunction()


Insert inline Markdown

Description

This function acceptsMarkdown-syntax text and returnsHTML that may be included in Shiny UIs.

Usage

markdown(mds, extensions = TRUE, .noWS = NULL, ...)

Arguments

mds

A character vector of Markdown source to convert to HTML. If thevector has more than one element, a single-element character vector ofconcatenated HTML is returned.

extensions

Enable Github syntax extensions; defaults toTRUE.

.noWS

Character vector used to omit some of the whitespace that wouldnormally be written around generated HTML. Valid options includebefore,after, andoutside (equivalent tobefore andend).

...

Additional arguments to pass tocommonmark::markdown_html().These arguments aredynamic.

Details

Leading whitespace is trimmed from Markdown text withglue::trim().Whitespace trimming ensures Markdown is processed correctly even when thecall tomarkdown() is indented within surrounding R code.

By default,Github extensions are enabled, but thiscan be disabled by passingextensions = FALSE.

Markdown rendering is performed bycommonmark::markdown_html(). Additionalarguments tomarkdown() are passed as arguments tomarkdown_html()

Value

a character vector marked as HTML.

Examples

ui <- fluidPage(  markdown("    # Markdown Example    This is a markdown paragraph, and will be contained within a `<p>` tag    in the UI.    The following is an unordered list, which will be represented in the UI as    a `<ul>` with `<li>` children:    * a bullet    * another    [Links](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a) work;    so does *emphasis*.    To see more of what's possible, check out [commonmark.org/help](https://commonmark.org/help).    "))

Evaluate an expression without a reactive context

Description

Temporarily blocks the current reactive context and evaluates the givenexpression. Any attempt to directly access reactive values or expressions inexpr will give the same results as doing it at the top-level (bydefault, an error).

Usage

maskReactiveContext(expr)

Arguments

expr

An expression to evaluate.

Value

The value ofexpr.

See Also

isolate()


Create memory cache (deprecated)

Description

Create memory cache (deprecated)

Usage

memoryCache(  max_size = 200 * 1024^2,  max_age = Inf,  max_n = Inf,  evict = c("lru", "fifo"),  missing = key_missing(),  exec_missing = deprecated(),  logfile = NULL)

Arguments

max_size

Maximum size of the cache, in bytes. If the cache exceedsthis size, cached objects will be removed according to the value of theevict. UseInf for no size limit. The default is 512 megabytes.

max_age

Maximum age of files in cache before they are evicted, inseconds. UseInf for no age limit.

max_n

Maximum number of objects in the cache. If the number of objectsexceeds this value, then cached objects will be removed according to thevalue ofevict. UseInf for no limit of number of items.

evict

The eviction policy to use to decide which objects are removedwhen a cache pruning occurs. Currently,"lru" and"fifo" are supported.

missing

A value to return whenget(key) is called but the key is notpresent in the cache. The default is akey_missing() object. It isactually an expression that is evaluated each time there is a cache miss.See section Missing keys for more information.

exec_missing

Deprecated.

logfile

An optional filename or connection object to where logginginformation will be written. To log to the console, usestderr() orstdout().


Create a modal dialog UI

Description

modalDialog() creates the UI for a modal dialog, using Bootstrap's modalclass. Modals are typically used for showing important messages, or forpresenting UI that requires input from the user, such as a user name andpassword input.

modalButton() creates a button that will dismiss the dialog when clicked,typically used when customising thefooter.

Usage

modalDialog(  ...,  title = NULL,  footer = modalButton("Dismiss"),  size = c("m", "s", "l", "xl"),  easyClose = FALSE,  fade = TRUE)modalButton(label, icon = NULL)

Arguments

...

UI elements for the body of the modal dialog box.

title

An optional title for the dialog.

footer

UI for footer. UseNULL for no footer.

size

One of"s" for small,"m" (the default) for medium,"l" for large, or"xl" for extra large. Note that"xl" onlyworks with Bootstrap 4 and above (to opt-in to Bootstrap 4+,passbslib::bs_theme() to thetheme argument of a page containerlikefluidPage()).

easyClose

IfTRUE, the modal dialog can be dismissed byclicking outside the dialog box, or be pressing the Escape key. IfFALSE (the default), the modal dialog can't be dismissed in thoseways; instead it must be dismissed by clicking on amodalButton(), orfrom a call toremoveModal() on the server.

fade

IfFALSE, the modal dialog will have no fade-in animation(it will simply appear rather than fade in to view).

label

The contents of the button or link–usually a text label, butyou could also use any other HTML, like an image.

icon

An optionalicon() to appear on the button.

Examples

if (interactive()) {# Display an important message that can be dismissed only by clicking the# dismiss button.shinyApp(  ui = basicPage(    actionButton("show", "Show modal dialog")  ),  server = function(input, output) {    observeEvent(input$show, {      showModal(modalDialog(        title = "Important message",        "This is an important message!"      ))    })  })# Display a message that can be dismissed by clicking outside the modal dialog,# or by pressing Esc.shinyApp(  ui = basicPage(    actionButton("show", "Show modal dialog")  ),  server = function(input, output) {    observeEvent(input$show, {      showModal(modalDialog(        title = "Somewhat important message",        "This is a somewhat important message.",        easyClose = TRUE,        footer = NULL      ))    })  })# Display a modal that requires valid input before continuing.shinyApp(  ui = basicPage(    actionButton("show", "Show modal dialog"),    verbatimTextOutput("dataInfo")  ),  server = function(input, output) {    # reactiveValues object for storing current data set.    vals <- reactiveValues(data = NULL)    # Return the UI for a modal dialog with data selection input. If 'failed' is    # TRUE, then display a message that the previous value was invalid.    dataModal <- function(failed = FALSE) {      modalDialog(        textInput("dataset", "Choose data set",          placeholder = 'Try "mtcars" or "abc"'        ),        span('(Try the name of a valid data object like "mtcars", ',             'then a name of a non-existent object like "abc")'),        if (failed)          div(tags$b("Invalid name of data object", style = "color: red;")),        footer = tagList(          modalButton("Cancel"),          actionButton("ok", "OK")        )      )    }    # Show modal when button is clicked.    observeEvent(input$show, {      showModal(dataModal())    })    # When OK button is pressed, attempt to load the data set. If successful,    # remove the modal. If not show another modal, but this time with a failure    # message.    observeEvent(input$ok, {      # Check that data object exists and is data frame.      if (!is.null(input$dataset) && nzchar(input$dataset) &&          exists(input$dataset) && is.data.frame(get(input$dataset))) {        vals$data <- get(input$dataset)        removeModal()      } else {        showModal(dataModal(failed = TRUE))      }    })    # Display information about selected data    output$dataInfo <- renderPrint({      if (is.null(vals$data))        "No data selected"      else        summary(vals$data)    })  })}

Shiny modules

Description

Shiny's module feature lets you break complicated UI and server logic intosmaller, self-contained pieces. Compared to large monolithic Shiny apps,modules are easier to reuse and easier to reason about. See the article athttps://shiny.rstudio.com/articles/modules.html to learn more.

Usage

moduleServer(id, module, session = getDefaultReactiveDomain())

Arguments

id

An ID string that corresponds with the ID used to call the module'sUI function.

module

A Shiny module server function.

session

Session from which to make a child scope (the default shouldalmost always be used).

Details

Starting in Shiny 1.5.0, we recommend usingmoduleServer instead ofcallModule(), because the syntax is a little easierto understand, and modules created withmoduleServer can be tested withtestServer().

Value

The return value, if any, from executing the module server function

See Also

https://shiny.rstudio.com/articles/modules.html

Examples

# Define the UI for a modulecounterUI <- function(id, label = "Counter") {  ns <- NS(id)  tagList(    actionButton(ns("button"), label = label),    verbatimTextOutput(ns("out"))  )}# Define the server logic for a modulecounterServer <- function(id) {  moduleServer(    id,    function(input, output, session) {      count <- reactiveVal(0)      observeEvent(input$button, {        count(count() + 1)      })      output$out <- renderText({        count()      })      count    }  )}# Use the module in an appui <- fluidPage(  counterUI("counter1", "Counter #1"),  counterUI("counter2", "Counter #2"))server <- function(input, output, session) {  counterServer("counter1")  counterServer("counter2")}if (interactive()) {  shinyApp(ui, server)}# If you want to pass extra parameters to the module's server logic, you can# add them to your function. In this case `prefix` is text that will be# printed before the count.counterServer2 <- function(id, prefix = NULL) {  moduleServer(    id,    function(input, output, session) {      count <- reactiveVal(0)      observeEvent(input$button, {        count(count() + 1)      })      output$out <- renderText({        paste0(prefix, count())      })      count    }  )}ui <- fluidPage(  counterUI("counter", "Counter"),)server <- function(input, output, session) {  counterServer2("counter", "The current count is: ")}if (interactive()) {  shinyApp(ui, server)}

Description

Create a page that contains a top level navigation bar that can be used totoggle a set oftabPanel() elements.

Usage

navbarPage(  title,  ...,  id = NULL,  selected = NULL,  position = c("static-top", "fixed-top", "fixed-bottom"),  header = NULL,  footer = NULL,  inverse = FALSE,  collapsible = FALSE,  fluid = TRUE,  theme = NULL,  windowTitle = NA,  lang = NULL)navbarMenu(title, ..., menuName = title, icon = NULL)

Arguments

title

The title to display in the navbar

...

tabPanel() elements to include in the page. ThenavbarMenu function also accepts strings, which will be used as menusection headers. If the string is a set of dashes like"----" ahorizontal separator will be displayed in the menu.

id

If provided, you can use⁠input$⁠id in yourserver logic to determine which of the current tabs is active. The valuewill correspond to thevalue argument that is passed totabPanel().

selected

Thevalue (or, if none was supplied, thetitle)of the tab that should be selected by default. IfNULL, the firsttab will be selected.

position

Determines whether the navbar should be displayed at the topof the page with normal scrolling behavior ("static-top"), pinned atthe top ("fixed-top"), or pinned at the bottom("fixed-bottom"). Note that using"fixed-top" or"fixed-bottom" will cause the navbar to overlay your body content,unless you add padding, e.g.:tags$style(type="text/css", "body {padding-top: 70px;}")

header

Tag or list of tags to display as a common header above alltabPanels.

footer

Tag or list of tags to display as a common footer below alltabPanels

inverse

TRUE to use a dark background and light text for thenavigation bar

collapsible

TRUE to automatically collapse the navigationelements into an expandable menu on mobile devices or narrow window widths.

fluid

TRUE to use a fluid layout.FALSE to use a fixedlayout.

theme

One of the following:

  • NULL (the default), which implies a "stock" build of Bootstrap 3.

  • Abslib::bs_theme() object. This can be used to replace a stockbuild of Bootstrap 3 with a customized version of Bootstrap 3 or higher.

  • A character string pointing to an alternative Bootstrap stylesheet(normally a css file within the www directory, e.g.www/bootstrap.css).

windowTitle

the browser window title (as a character string). Thedefault value,NA, means to use any character strings that appear intitle (if none are found, the host URL of the page is displayed bydefault).

lang

ISO 639-1 language code for the HTML page, such as "en" or "ko".This will be used as the lang in the<html> tag, as in<html lang="en">.The default (NULL) results in an empty string.

menuName

A name that identifies thisnavbarMenu. Thisis needed if you want to insert/remove or show/hide an entirenavbarMenu.

icon

Optional icon to appear on anavbarMenu tab.

Details

ThenavbarMenu function can be used to create an embeddedmenu within the navbar that in turns includes additional tabPanels (seeexample below).

Value

A UI definition that can be passed to theshinyUI function.

See Also

tabPanel(),tabsetPanel(),updateNavbarPage(),insertTab(),showTab()

Other layout functions:fillPage(),fixedPage(),flowLayout(),fluidPage(),sidebarLayout(),splitLayout(),verticalLayout()

Examples

navbarPage("App Title",  tabPanel("Plot"),  tabPanel("Summary"),  tabPanel("Table"))navbarPage("App Title",  tabPanel("Plot"),  navbarMenu("More",    tabPanel("Summary"),    "----",    "Section header",    tabPanel("Table")  ))

Description

Create a navigation list panel that provides a list of links on the leftwhich navigate to a set of tabPanels displayed to the right.

Usage

navlistPanel(  ...,  id = NULL,  selected = NULL,  header = NULL,  footer = NULL,  well = TRUE,  fluid = TRUE,  widths = c(4, 8))

Arguments

...

tabPanel() elements to include in the navlist

id

If provided, you can use⁠input$⁠id in yourserver logic to determine which of the current navlist items is active. Thevalue will correspond to thevalue argument that is passed totabPanel().

selected

Thevalue (or, if none was supplied, thetitle)of the navigation item that should be selected by default. IfNULL,the first navigation will be selected.

header

Tag or list of tags to display as a common header above alltabPanels.

footer

Tag or list of tags to display as a common footer below alltabPanels

well

TRUE to place a well (gray rounded rectangle) around thenavigation list.

fluid

TRUE to use fluid layout;FALSE to use fixedlayout.

widths

Column widths of the navigation list and tabset content areasrespectively.

Details

You can include headers within thenavlistPanel by includingplain text elements in the list. Versions of Shiny before 0.11 supportedseparators with "——", but as of 0.11, separators were no longersupported. This is because version 0.11 switched to Bootstrap 3, whichdoesn't support separators.

See Also

tabPanel(),updateNavlistPanel(),insertTab(),showTab()

Examples

fluidPage(  titlePanel("Application Title"),  navlistPanel(    "Header",    tabPanel("First"),    tabPanel("Second"),    tabPanel("Third")  ))

Create a numeric input control

Description

Create an input control for entry of numeric values

Usage

numericInput(  inputId,  label,  value,  min = NA,  max = NA,  step = NA,  width = NULL,  ...,  updateOn = c("change", "blur"))

Arguments

inputId

Theinput slot that will be used to access the value.

label

Display label for the control, orNULL for no label.

value

Initial value.

min

Minimum allowed value

max

Maximum allowed value

step

Interval to use when stepping between min and max

width

The width of the input, e.g.'400px', or'100%';seevalidateCssUnit().

...

Ignored, included to require named arguments and for futurefeature expansion.

updateOn

A character vector specifying when the input should beupdated. Options are"change" (default) and"blur". Use"change" toupdate the input immediately whenever the value changes. Use"blur"todelay the input update until the input loses focus (the user moves awayfrom the input), or when Enter is pressed (or Cmd/Ctrl + Enter fortextAreaInput()).

Value

A numeric input control that can be added to a UI definition.

Server value

A numeric vector of length 1.

See Also

updateNumericInput()

Other input elements:actionButton(),checkboxGroupInput(),checkboxInput(),dateInput(),dateRangeInput(),fileInput(),passwordInput(),radioButtons(),selectInput(),sliderInput(),submitButton(),textAreaInput(),textInput(),varSelectInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  numericInput("obs", "Observations:", 10, min = 1, max = 100),  verbatimTextOutput("value"))server <- function(input, output) {  output$value <- renderText({ input$obs })}shinyApp(ui, server)}

Create a reactive observer

Description

Creates an observer from the given expression.

Usage

observe(  x,  env = parent.frame(),  quoted = FALSE,  ...,  label = NULL,  suspended = FALSE,  priority = 0,  domain = getDefaultReactiveDomain(),  autoDestroy = TRUE,  ..stacktraceon = TRUE)

Arguments

x

An expression (quoted or unquoted). Any return value will beignored.

env

The parent environment for the reactive expression. By default,this is the calling environment, the same as when defining an ordinarynon-reactive expression. Ifx is a quosure andquoted isTRUE,thenenv is ignored.

quoted

If it isTRUE, then thequote()ed value ofxwill be used whenx is evaluated. Ifx is a quosure and youwould like to use its expression as a value forx, then you must setquoted toTRUE.

...

Not used.

label

A label for the observer, useful for debugging.

suspended

IfTRUE, start the observer in a suspended state. IfFALSE (the default), start in a non-suspended state.

priority

An integer or numeric that controls the priority with whichthis observer should be executed. A higher value means higher priority: anobserver with a higher priority value will execute before all observerswith lower priority values. Positive, negative, and zero values areallowed.

domain

Seedomains.

autoDestroy

IfTRUE (the default), the observer will beautomatically destroyed when its domain (if any) ends.

..stacktraceon

Advanced use only. For stack manipulation purposes; seestacktrace().

Details

An observer is like a reactive expression in that it can read reactive valuesand call reactive expressions, and will automatically re-execute when thosedependencies change. But unlike reactive expressions, it doesn't yield aresult and can't be used as an input to other reactive expressions. Thus,observers are only useful for their side effects (for example, performingI/O).

Another contrast between reactive expressions and observers is theirexecution strategy. Reactive expressions use lazy evaluation; that is, whentheir dependencies change, they don't re-execute right away but rather waituntil they are called by someone else. Indeed, if they are not called thenthey will never re-execute. In contrast, observers use eager evaluation; assoon as their dependencies change, they schedule themselves to re-execute.

Starting with Shiny 0.10.0, observers are automatically destroyed by defaultwhen thedomain that owns them ends (e.g. when a Shinysession ends).

Value

An observer reference class object. This object has the followingmethods:

suspend()

Causes this observer to stop scheduling flushes (re-executions) inresponse to invalidations. If the observer was invalidated prior tothis call but it has not re-executed yet then that re-execution willstill occur, because the flush is already scheduled.

resume()

Causes this observer to start re-executing in response toinvalidations. If the observer was invalidated while suspended, then itwill schedule itself for re-execution.

destroy()

Stops the observer from executing ever again, even if it is currentlyscheduled for re-execution.

setPriority(priority = 0)

Change this observer's priority. Note that if the observer is currentlyinvalidated, then the change in priority will not take effect until thenext invalidation–unless the observer is also currently suspended, inwhich case the priority change will be effective upon resume.

setAutoDestroy(autoDestroy)

Sets whether this observer should be automatically destroyed when itsdomain (if any) ends. If autoDestroy is TRUE and the domain alreadyended, then destroy() is called immediately."

onInvalidate(callback)

Register a callback function to run when this observer is invalidated.No arguments will be provided to the callback function when it isinvoked.

Examples

values <- reactiveValues(A=1)obsB <- observe({  print(values$A + 1)})# To store expressions for later conversion to observe, use rlang::quo()myquo <- rlang::quo({ print(values$A + 3) })obsC <- rlang::inject(observe(!!myquo))# (Legacy) Can use quoted expressionsobsD <- observe(quote({ print(values$A + 2) }), quoted = TRUE)# In a normal Shiny app, the web client will trigger flush events. If you# are at the console, you can force a flush with flushReact()shiny:::flushReact()

Event handler

Description

Respond to "event-like" reactive inputs, values, and expressions. As of Shiny1.6.0, we recommend usingbindEvent() instead ofeventReactive() andobserveEvent(). This is becausebindEvent() can be composed withbindCache(), and because it can also be used withrender functions (likerenderText() andrenderPlot()).

Usage

observeEvent(  eventExpr,  handlerExpr,  event.env = parent.frame(),  event.quoted = FALSE,  handler.env = parent.frame(),  handler.quoted = FALSE,  ...,  label = NULL,  suspended = FALSE,  priority = 0,  domain = getDefaultReactiveDomain(),  autoDestroy = TRUE,  ignoreNULL = TRUE,  ignoreInit = FALSE,  once = FALSE)eventReactive(  eventExpr,  valueExpr,  event.env = parent.frame(),  event.quoted = FALSE,  value.env = parent.frame(),  value.quoted = FALSE,  ...,  label = NULL,  domain = getDefaultReactiveDomain(),  ignoreNULL = TRUE,  ignoreInit = FALSE)

Arguments

eventExpr

A (quoted or unquoted) expression that represents the event;this can be a simple reactive value likeinput$click, a call to areactive expression likedataset(), or even a complex expressioninside curly braces

handlerExpr

The expression to call whenevereventExpr isinvalidated. This should be a side-effect-producing action (the returnvalue will be ignored). It will be executed within anisolate()scope.

event.env

The parent environment for the reactive expression. By default,this is the calling environment, the same as when defining an ordinarynon-reactive expression. IfeventExpr is a quosure andevent.quoted isTRUE,thenevent.env is ignored.

event.quoted

If it isTRUE, then thequote()ed value ofeventExprwill be used wheneventExpr is evaluated. IfeventExpr is a quosure and youwould like to use its expression as a value foreventExpr, then you must setevent.quoted toTRUE.

handler.env

The parent environment for the reactive expression. By default,this is the calling environment, the same as when defining an ordinarynon-reactive expression. IfhandlerExpr is a quosure andhandler.quoted isTRUE,thenhandler.env is ignored.

handler.quoted

If it isTRUE, then thequote()ed value ofhandlerExprwill be used whenhandlerExpr is evaluated. IfhandlerExpr is a quosure and youwould like to use its expression as a value forhandlerExpr, then you must sethandler.quoted toTRUE.

...

Currently not used.

label

A label for the observer or reactive, useful for debugging.

suspended

IfTRUE, start the observer in a suspended state. IfFALSE (the default), start in a non-suspended state.

priority

An integer or numeric that controls the priority with whichthis observer should be executed. An observer with a given priority levelwill always execute sooner than all observers with a lower priority level.Positive, negative, and zero values are allowed.

domain

Seedomains.

autoDestroy

IfTRUE (the default), the observer will beautomatically destroyed when its domain (if any) ends.

ignoreNULL

Whether the action should be triggered (or valuecalculated, in the case ofeventReactive) when the input event expressionisNULL. See Details.

ignoreInit

IfTRUE, then, when thisobserveEvent isfirst created/initialized, ignore thehandlerExpr (the secondargument), whether it is otherwise supposed to run or not. The default isFALSE. See Details.

once

Whether thisobserveEvent should be immediately destroyedafter the first time that the code inhandlerExpr is run. Thispattern is useful when you want to subscribe to a event that should onlyhappen once.

valueExpr

The expression that produces the return value of theeventReactive. It will be executed within anisolate()scope.

value.env

The parent environment for the reactive expression. By default,this is the calling environment, the same as when defining an ordinarynon-reactive expression. IfvalueExpr is a quosure andvalue.quoted isTRUE,thenvalue.env is ignored.

value.quoted

If it isTRUE, then thequote()ed value ofvalueExprwill be used whenvalueExpr is evaluated. IfvalueExpr is a quosure and youwould like to use its expression as a value forvalueExpr, then you must setvalue.quoted toTRUE.

Details

Shiny's reactive programming framework is primarily designed for calculatedvalues (reactive expressions) and side-effect-causing actions (observers)that respond toany of their inputs changing. That's often what isdesired in Shiny apps, but not always: sometimes you want to wait for aspecific action to be taken from the user, like clicking anactionButton(), before calculating an expression or taking anaction. A reactive value or expression that is used to trigger othercalculations in this way is called anevent.

These situations demand a more imperative, "event handling" style ofprogramming that is possible–but not particularly intuitive–using thereactive programming primitivesobserve() andisolate().observeEvent andeventReactive providestraightforward APIs for event handling that wrapobserve andisolate.

UseobserveEvent whenever you want toperform an action inresponse to an event. (Note that "recalculate a value" does not generallycount as performing an action–seeeventReactive for that.) The firstargument is the event you want to respond to, and the second argument is afunction that should be called whenever the event occurs. Note thatobserveEvent() is equivalent to usingobserve() %>% bindEvent() and as ofShiny 1.6.0, we recommend the latter.

UseeventReactive to create acalculated value that onlyupdates in response to an event. This is just like a normalreactive expression except it ignores all the usualinvalidations that come from its reactive dependencies; it only invalidatesin response to the given event. Note thateventReactive() is equivalent to usingreactive() %>% bindEvent() and as ofShiny 1.6.0, we recommend the latter.

Value

observeEvent returns an observer reference class object (seeobserve()).eventReactive returns a reactive expressionobject (seereactive()).

ignoreNULL and ignoreInit

BothobserveEvent andeventReactive take anignoreNULLparameter that affects behavior when theeventExpr evaluates toNULL (or in the special case of anactionButton(),0). In these cases, ifignoreNULL isTRUE, then anobserveEvent will not execute and aneventReactive will raise asilentvalidation error. This is useful behavior if youdon't want to do the action or calculation when your app first starts, butwait for the user to initiate the action first (like a "Submit" button);whereasignoreNULL=FALSE is desirable if you want to initially performthe action/calculation and just let the user re-initiate it (like a"Recalculate" button).

Likewise, bothobserveEvent andeventReactive also take in anignoreInit argument. By default, both of these will run right when theyare created (except if, at that moment,eventExpr evaluates toNULLandignoreNULL isTRUE). But when responding to a click of an actionbutton, it may often be useful to setignoreInit toTRUE. Forexample, if you're setting up anobserveEvent for a dynamically createdbutton, thenignoreInit = TRUE will guarantee that the action (inhandlerExpr) will only be triggered when the button is actually clicked,instead of also being triggered when it is created/initialized. Similarly,if you're setting up aneventReactive that responds to a dynamicallycreated button used to refresh some data (then returned by thateventReactive),then you should use⁠eventReactive([...], ignoreInit = TRUE)⁠ if you wantto let the user decide if/when they want to refresh the data (since, dependingon the app, this may be a computationally expensive operation).

Even thoughignoreNULL andignoreInit can be used for similarpurposes they are independent from one another. Here's the result of combiningthese:

ignoreNULL = TRUE andignoreInit = FALSE

This is the default. This combination means thathandlerExpr/valueExpr will run every time thateventExpr is notNULL. If, at the time of the creation of theobserveEvent/eventReactive,eventExpr happenstonot beNULL, then the code runs.

ignoreNULL = FALSE andignoreInit = FALSE

This combination means thathandlerExpr/valueExpr willrun every time no matter what.

ignoreNULL = FALSE andignoreInit = TRUE

This combination means thathandlerExpr/valueExpr willnot run when theobserveEvent/eventReactive iscreated (becauseignoreInit = TRUE), but it will run everyother time.

ignoreNULL = TRUE andignoreInit = TRUE

This combination means thathandlerExpr/valueExpr willnot run when theobserveEvent/eventReactive iscreated (becauseignoreInit = TRUE). After that,handlerExpr/valueExpr will run every time thateventExpr is notNULL.

See Also

actionButton()

Examples

## Only run examples in interactive R sessionsif (interactive()) {  ## App 1: Sample usage  shinyApp(    ui = fluidPage(      column(4,        numericInput("x", "Value", 5),        br(),        actionButton("button", "Show")      ),      column(8, tableOutput("table"))    ),    server = function(input, output) {      # Take an action every time button is pressed;      # here, we just print a message to the console      observeEvent(input$button, {        cat("Showing", input$x, "rows\n")      })      # The observeEvent() above is equivalent to:      # observe({      #    cat("Showing", input$x, "rows\n")      #   }) %>%      #   bindEvent(input$button)      # Take a reactive dependency on input$button, but      # not on any of the stuff inside the function      df <- eventReactive(input$button, {        head(cars, input$x)      })      output$table <- renderTable({        df()      })    }  )  ## App 2: Using `once`  shinyApp(    ui = basicPage( actionButton("go", "Go")),    server = function(input, output, session) {      observeEvent(input$go, {        print(paste("This will only be printed once; all",              "subsequent button clicks won't do anything"))      }, once = TRUE)      # The observeEvent() above is equivalent to:      # observe({      #   print(paste("This will only be printed once; all",      #         "subsequent button clicks won't do anything"))      #   }) %>%      #   bindEvent(input$go, once = TRUE)    }  )  ## App 3: Using `ignoreInit` and `once`  shinyApp(    ui = basicPage(actionButton("go", "Go")),    server = function(input, output, session) {      observeEvent(input$go, {        insertUI("#go", "afterEnd",                 actionButton("dynamic", "click to remove"))        # set up an observer that depends on the dynamic        # input, so that it doesn't run when the input is        # created, and only runs once after that (since        # the side effect is remove the input from the DOM)        observeEvent(input$dynamic, {          removeUI("#dynamic")        }, ignoreInit = TRUE, once = TRUE)      })    }  )}

Add callbacks for Shiny session bookmarking events

Description

These functions are for registering callbacks on Shiny session events. Theyshould be called within an application's server function.

Usage

onBookmark(fun, session = getDefaultReactiveDomain())onBookmarked(fun, session = getDefaultReactiveDomain())onRestore(fun, session = getDefaultReactiveDomain())onRestored(fun, session = getDefaultReactiveDomain())

Arguments

fun

A callback function which takes one argument.

session

A shiny session object.

Details

All of these functions return a function which can be called with noarguments to cancel the registration.

The callback function that is passed to these functions should take oneargument, typically named "state" (foronBookmark,onRestore,andonRestored) or "url" (foronBookmarked).

ForonBookmark, the state object has three relevant fields. Thevalues field is an environment which can be used to save arbitraryvalues (see examples). If the state is being saved to disk (as opposed tobeing encoded in a URL), thedir field contains the name of adirectory which can be used to store extra files. Finally, the state objecthas aninput field, which is simply the application'sinputobject. It can be read, but not modified.

ForonRestore andonRestored, the state object is a list. Thislist containsinput, which is a named list of input values to restore,values, which is an environment containing arbitrary values that weresaved inonBookmark, anddir, the name of the directory thatthe state is being restored from, and which could have been used to saveextra files.

ForonBookmarked, the callback function receives a string with thebookmark URL. This callback function should be used to display UI in theclient browser with the bookmark URL. If no callback function is registered,then Shiny will by default display a modal dialog with the bookmark URL.

Modules

These callbacks may also be used in Shiny modules. When used this way, theinputs and values will automatically be namespaced for the module, and thecallback functions registered for the module will only be able to see themodule's inputs and values.

See Also

enableBookmarking for general information on bookmarking.

Examples

## Only run these examples in interactive sessionsif (interactive()) {# Basic use of onBookmark and onRestore: This app saves the time in its# arbitrary values, and restores that time when the app is restored.ui <- function(req) {  fluidPage(    textInput("txt", "Input text"),    bookmarkButton()  )}server <- function(input, output) {  onBookmark(function(state) {    savedTime <- as.character(Sys.time())    cat("Last saved at", savedTime, "\n")    # state is a mutable reference object, and we can add arbitrary values to    # it.    state$values$time <- savedTime  })  onRestore(function(state) {    cat("Restoring from state bookmarked at", state$values$time, "\n")  })}enableBookmarking("url")shinyApp(ui, server)ui <- function(req) {  fluidPage(    textInput("txt", "Input text"),    bookmarkButton()  )}server <- function(input, output, session) {  lastUpdateTime <- NULL  observeEvent(input$txt, {    updateTextInput(session, "txt",      label = paste0("Input text (Changed ", as.character(Sys.time()), ")")    )  })  onBookmark(function(state) {    # Save content to a file    messageFile <- file.path(state$dir, "message.txt")    cat(as.character(Sys.time()), file = messageFile)  })  onRestored(function(state) {    # Read the file    messageFile <- file.path(state$dir, "message.txt")    timeText <- readChar(messageFile, 1000)    # updateTextInput must be called in onRestored, as opposed to onRestore,    # because onRestored happens after the client browser is ready.    updateTextInput(session, "txt",      label = paste0("Input text (Changed ", timeText, ")")    )  })}# "server" bookmarking is needed for writing to disk.enableBookmarking("server")shinyApp(ui, server)# This app has a module, and both the module and the main app code have# onBookmark and onRestore functions which write and read state$values$hash. The# module's version of state$values$hash does not conflict with the app's version# of state$values$hash.## A basic module that captializes text.capitalizerUI <- function(id) {  ns <- NS(id)  wellPanel(    h4("Text captializer module"),    textInput(ns("text"), "Enter text:"),    verbatimTextOutput(ns("out"))  )}capitalizerServer <- function(input, output, session) {  output$out <- renderText({    toupper(input$text)  })  onBookmark(function(state) {    state$values$hash <- rlang::hash(input$text)  })  onRestore(function(state) {    if (identical(rlang::hash(input$text), state$values$hash)) {      message("Module's input text matches hash ", state$values$hash)    } else {      message("Module's input text does not match hash ", state$values$hash)    }  })}# Main app codeui <- function(request) {  fluidPage(    sidebarLayout(      sidebarPanel(        capitalizerUI("tc"),        textInput("text", "Enter text (not in module):"),        bookmarkButton()      ),      mainPanel()    )  )}server <- function(input, output, session) {  callModule(capitalizerServer, "tc")  onBookmark(function(state) {    state$values$hash <- rlang::hash(input$text)  })  onRestore(function(state) {    if (identical(rlang::hash(input$text), state$values$hash)) {      message("App's input text matches hash ", state$values$hash)    } else {      message("App's input text does not match hash ", state$values$hash)    }  })}enableBookmarking(store = "url")shinyApp(ui, server)}

Add callbacks for Shiny session events

Description

These functions are for registering callbacks on Shiny session events.onFlush registers a function that will be called before Shiny flushes thereactive system.onFlushed registers a function that will be called afterShiny flushes the reactive system.onUnhandledError registers a function tobe called when an unhandled error occurs before the session is closed.onSessionEnded registers a function to be called after the client hasdisconnected.

These functions should be called within the application's server function.

All of these functions return a function which can be called with noarguments to cancel the registration.

Usage

onFlush(fun, once = TRUE, session = getDefaultReactiveDomain())onFlushed(fun, once = TRUE, session = getDefaultReactiveDomain())onSessionEnded(fun, session = getDefaultReactiveDomain())onUnhandledError(fun, session = getDefaultReactiveDomain())

Arguments

fun

A callback function.

once

Should the function be run once, and then cleared, or should itre-run each time the event occurs. (Only foronFlush andonFlushed.)

session

A shiny session object.

Unhandled Errors

Unhandled errors are errors that aren't otherwise handled by Shiny or by theapplication logic. In other words, they are errors that will either cause theapplication to crash or will result in "Error" output in the UI.

You can useonUnhandledError() to register a function that will be calledwhen an unhandled error occurs. This function will be called with the errorobject as its first argument. If the error is fatal and will result in thesession closing, the error condition will have theshiny.error.fatal class.

Note that theonUnhandledError() callbacks cannot be used to prevent theapp from closing or to modify the error condition. Instead, they are intendedto give you an opportunity to log the error or perform other cleanupoperations.

See Also

onStop() for registering callbacks that will beinvoked when the application exits, or when a session ends.

Examples

library(shiny)ui <- fixedPage(  markdown(c(    "Set the number to 8 or higher to cause an error",    "in the `renderText()` output."  )),  sliderInput("number", "Number", 0, 10, 4),  textOutput("text"),  hr(),  markdown(c(    "Click the button below to crash the app with an unhandled error",    "in an `observe()` block."  )),  actionButton("crash", "Crash the app!"))log_event <- function(level, ...) {  ts <- strftime(Sys.time(), " [%F %T] ")  message(level, ts, ...)}server <- function(input, output, session) {  log_event("INFO", "Session started")  onUnhandledError(function(err) {    # log the unhandled error    level <- if (inherits(err, "shiny.error.fatal")) "FATAL" else "ERROR"    log_event(level, conditionMessage(err))  })  onStop(function() {    log_event("INFO", "Session ended")  })  observeEvent(input$crash, stop("Oops, an unhandled error happened!"))  output$text <- renderText({    if (input$number > 7) {      stop("that's too high!")    }    sprintf("You picked number %d.", input$number)  })}shinyApp(ui, server)

Run code after an application or session ends

Description

This function registers callback functions that are invoked when theapplication exits (whenrunApp() exits), or after each usersession ends (when a client disconnects).

Usage

onStop(fun, session = getDefaultReactiveDomain())

Arguments

fun

A function that will be called after the app has finished running.

session

A scope for when the callback will run. IfonStop iscalled from within the server function, this will default to the currentsession, and the callback will be invoked when the current session ends. IfonStop is called outside a server function, then the callback willbe invoked with the application exits. IfNULL, it is the same ascallingonStop outside of the server function, and the callback willbe invoked when the application exits.

Value

A function which, if invoked, will cancel the callback.

See Also

onSessionEnded() for the same functionality, but atthe session level only.

Examples

## Only run this example in interactive R sessionsif (interactive()) {  # Open this application in multiple browsers, then close the browsers.  shinyApp(    ui = basicPage("onStop demo"),    server = function(input, output, session) {      onStop(function() cat("Session stopped\n"))    },    onStart = function() {      cat("Doing application setup\n")      onStop(function() {        cat("Doing application cleanup\n")      })    }  )}# In the example above, onStop() is called inside of onStart(). This is# the pattern that should be used when creating a shinyApp() object from# a function, or at the console. If instead you are writing an app.R which# will be invoked with runApp(), you can do it that way, or put the onStop()# before the shinyApp() call, as shown below.## Not run: # ==== app.R ====cat("Doing application setup\n")onStop(function() {  cat("Doing application cleanup\n")})shinyApp(  ui = basicPage("onStop demo"),  server = function(input, output, session) {    onStop(function() cat("Session stopped\n"))  })# ==== end app.R ====# Similarly, if you have a global.R, you can call onStop() from there.# ==== global.R ====cat("Doing application setup\n")onStop(function() {  cat("Doing application cleanup\n")})# ==== end global.R ====## End(Not run)

Set options for an output object.

Description

These are the available options for an output object:

Usage

outputOptions(x, name, ...)

Arguments

x

A shinyoutput object (typicallyoutput).

name

The name of an output observer in the shinyoutput object.

...

Options to set for the output observer.

Examples

## Not run: # Get the list of options for all observers within outputoutputOptions(output)# Disable suspend for output$myplotoutputOptions(output, "myplot", suspendWhenHidden = FALSE)# Change priority for output$myplotoutputOptions(output, "myplot", priority = 10)# Get the list of options for output$myplotoutputOptions(output, "myplot")## End(Not run)

Create a page with a sidebar

Description

DEPRECATED: usefluidPage() andsidebarLayout() instead.

Usage

pageWithSidebar(headerPanel, sidebarPanel, mainPanel)

Arguments

headerPanel

TheheaderPanel with the application title

sidebarPanel

ThesidebarPanel containing input controls

mainPanel

ThemainPanel containing outputs

Value

A UI definition that can be passed to theshinyUI function


Parse a GET query string from a URL

Description

Returns a named list of key-value pairs.

Usage

parseQueryString(str, nested = FALSE)

Arguments

str

The query string. It can have a leading"?" or not.

nested

Whether to parse the query string of as a nested list when itcontains pairs of square brackets[]. For example, the query‘⁠a[i1][j1]=x&b[i1][j1]=y&b[i2][j1]=z⁠’ will be parsed aslist(a =list(i1 = list(j1 = 'x')), b = list(i1 = list(j1 = 'y'), i2 = list(j1 ='z'))) whennested = TRUE, andlist(`a[i1][j1]` = 'x',`b[i1][j1]` = 'y', `b[i2][j1]` = 'z') whennested = FALSE.

Examples

parseQueryString("?foo=1&bar=b%20a%20r")## Not run: # Example of usage within a Shiny appfunction(input, output, session) {  output$queryText <- renderText({    query <- parseQueryString(session$clientData$url_search)    # Ways of accessing the values    if (as.numeric(query$foo) == 1) {      # Do something    }    if (query[["bar"]] == "targetstring") {      # Do something else    }    # Return a string with key-value pairs    paste(names(query), query, sep = "=", collapse=", ")  })}## End(Not run)

Create a password input control

Description

Create an password control for entry of passwords.

Usage

passwordInput(  inputId,  label,  value = "",  width = NULL,  placeholder = NULL,  ...,  updateOn = c("change", "blur"))

Arguments

inputId

Theinput slot that will be used to access the value.

label

Display label for the control, orNULL for no label.

value

Initial value.

width

The width of the input, e.g.'400px', or'100%';seevalidateCssUnit().

placeholder

A character string giving the user a hint as to what canbe entered into the control. Internet Explorer 8 and 9 do not support thisoption.

...

Ignored, included to require named arguments and for futurefeature expansion.

updateOn

A character vector specifying when the input should beupdated. Options are"change" (default) and"blur". Use"change" toupdate the input immediately whenever the value changes. Use"blur"todelay the input update until the input loses focus (the user moves awayfrom the input), or when Enter is pressed (or Cmd/Ctrl + Enter fortextAreaInput()).

Value

A text input control that can be added to a UI definition.

Server value

A character string of the password input. The default value is""unlessvalue is provided.

See Also

updateTextInput()

Other input elements:actionButton(),checkboxGroupInput(),checkboxInput(),dateInput(),dateRangeInput(),fileInput(),numericInput(),radioButtons(),selectInput(),sliderInput(),submitButton(),textAreaInput(),textInput(),varSelectInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  passwordInput("password", "Password:"),  actionButton("go", "Go"),  verbatimTextOutput("value"))server <- function(input, output) {  output$value <- renderText({    req(input$go)    isolate(input$password)  })}shinyApp(ui, server)}

Create an plot or image output element

Description

Render arenderPlot() orrenderImage() within anapplication page.

Usage

imageOutput(  outputId,  width = "100%",  height = "400px",  click = NULL,  dblclick = NULL,  hover = NULL,  brush = NULL,  inline = FALSE,  fill = FALSE)plotOutput(  outputId,  width = "100%",  height = "400px",  click = NULL,  dblclick = NULL,  hover = NULL,  brush = NULL,  inline = FALSE,  fill = !inline)

Arguments

outputId

output variable to read the plot/image from.

width,height

Image width/height. Must be a valid CSS unit (like"100%","400px","auto") or a number, which will becoerced to a string and have"px" appended. These two arguments areignored wheninline = TRUE, in which case the width/height of a plotmust be specified inrenderPlot(). Note that, for height, using"auto" or"100%" generally will not work as expected,because of how height is computed with HTML/CSS.

click

This can beNULL (the default), a string, or an objectcreated by theclickOpts() function. If you use a value like"plot_click" (or equivalently,clickOpts(id="plot_click")),the plot will send coordinates to the server whenever it is clicked, andthe value will be accessible viainput$plot_click. The value will bea named list withx andy elements indicating the mouseposition.

dblclick

This is just like theclick argument, but fordouble-click events.

hover

Similar to theclick argument, this can beNULL(the default), a string, or an object created by thehoverOpts() function. If you use a value like"plot_hover" (or equivalently,hoverOpts(id="plot_hover")),the plot will send coordinates to the server pauses on the plot, and thevalue will be accessible viainput$plot_hover. The value will be anamed list withx andy elements indicating the mouseposition. To control the hover time or hover delay type, you must usehoverOpts().

brush

Similar to theclick argument, this can beNULL(the default), a string, or an object created by thebrushOpts() function. If you use a value like"plot_brush" (or equivalently,brushOpts(id="plot_brush")),the plot will allow the user to "brush" in the plotting area, and will sendinformation about the brushed area to the server, and the value will beaccessible viainput$plot_brush. Brushing means that the user willbe able to draw a rectangle in the plotting area and drag it around. Thevalue will be a named list withxmin,xmax,ymin, andymax elements indicating the brush area. To control the brushbehavior, usebrushOpts(). MultipleimageOutput/plotOutput calls may share the sameidvalue; brushing one image or plot will cause any other brushes with thesameid to disappear.

inline

use an inline (span()) or block container (div())for the output

fill

Whether or not the returned tag should be treated as a fill item,meaning that itsheight is allowed to grow/shrink to fit a fill containerwith an opinionated height (seehtmltools::bindFillRole()) with anopinionated height. Examples of fill containers includebslib::card() andbslib::card_body_fill().

Value

A plot or image output element that can be included in a panel.

Interactive plots

Plots and images in Shiny support mouse-based interaction, via clicking,double-clicking, hovering, and brushing. When these interaction eventsoccur, the mouse coordinates will be sent to the server as⁠input$⁠variables, as specified byclick,dblclick,hover, orbrush.

ForplotOutput, the coordinates will be sent scaled to the dataspace, if possible. (At the moment, plots generated by base graphics andggplot2 support this scaling, although plots generated by lattice andothers do not.) If scaling is not possible, the raw pixel coordinates willbe sent. ForimageOutput, the coordinates will be sent in raw pixelcoordinates.

With ggplot2 graphics, the code inrenderPlot should return a ggplotobject; if instead the code prints the ggplot2 object with something likeprint(p), then the coordinates for interactive graphics will not beproperly scaled to the data space.

Note

The argumentsclickId andhoverId only work for R base graphics(see thegraphics package). They donot work forgrid-based graphics, such asggplot2,lattice, and so on.

See Also

For the corresponding server-side functions, seerenderPlot() andrenderImage().

Examples

# Only run these examples in interactive R sessionsif (interactive()) {# A basic shiny app with a plotOutputshinyApp(  ui = fluidPage(    sidebarLayout(      sidebarPanel(        actionButton("newplot", "New plot")      ),      mainPanel(        plotOutput("plot")      )    )  ),  server = function(input, output) {    output$plot <- renderPlot({      input$newplot      # Add a little noise to the cars data      cars2 <- cars + rnorm(nrow(cars))      plot(cars2)    })  })# A demonstration of clicking, hovering, and brushingshinyApp(  ui = basicPage(    fluidRow(      column(width = 4,        plotOutput("plot", height=300,          click = "plot_click",  # Equiv, to click=clickOpts(id="plot_click")          hover = hoverOpts(id = "plot_hover", delayType = "throttle"),          brush = brushOpts(id = "plot_brush")        ),        h4("Clicked points"),        tableOutput("plot_clickedpoints"),        h4("Brushed points"),        tableOutput("plot_brushedpoints")      ),      column(width = 4,        verbatimTextOutput("plot_clickinfo"),        verbatimTextOutput("plot_hoverinfo")      ),      column(width = 4,        wellPanel(actionButton("newplot", "New plot")),        verbatimTextOutput("plot_brushinfo")      )    )  ),  server = function(input, output, session) {    data <- reactive({      input$newplot      # Add a little noise to the cars data so the points move      cars + rnorm(nrow(cars))    })    output$plot <- renderPlot({      d <- data()      plot(d$speed, d$dist)    })    output$plot_clickinfo <- renderPrint({      cat("Click:\n")      str(input$plot_click)    })    output$plot_hoverinfo <- renderPrint({      cat("Hover (throttled):\n")      str(input$plot_hover)    })    output$plot_brushinfo <- renderPrint({      cat("Brush (debounced):\n")      str(input$plot_brush)    })    output$plot_clickedpoints <- renderTable({      # For base graphics, we need to specify columns, though for ggplot2,      # it's usually not necessary.      res <- nearPoints(data(), input$plot_click, "speed", "dist")      if (nrow(res) == 0)        return()      res    })    output$plot_brushedpoints <- renderTable({      res <- brushedPoints(data(), input$plot_brush, "speed", "dist")      if (nrow(res) == 0)        return()      res    })  })# Demo of clicking, hovering, brushing with imageOutput# Note that coordinates are in pixelsshinyApp(  ui = basicPage(    fluidRow(      column(width = 4,        imageOutput("image", height=300,          click = "image_click",          hover = hoverOpts(            id = "image_hover",            delay = 500,            delayType = "throttle"          ),          brush = brushOpts(id = "image_brush")        )      ),      column(width = 4,        verbatimTextOutput("image_clickinfo"),        verbatimTextOutput("image_hoverinfo")      ),      column(width = 4,        wellPanel(actionButton("newimage", "New image")),        verbatimTextOutput("image_brushinfo")      )    )  ),  server = function(input, output, session) {    output$image <- renderImage({      input$newimage      # Get width and height of image output      width  <- session$clientData$output_image_width      height <- session$clientData$output_image_height      # Write to a temporary PNG file      outfile <- tempfile(fileext = ".png")      png(outfile, width=width, height=height)      plot(rnorm(200), rnorm(200))      dev.off()      # Return a list containing information about the image      list(        src = outfile,        contentType = "image/png",        width = width,        height = height,        alt = "This is alternate text"      )    })    output$image_clickinfo <- renderPrint({      cat("Click:\n")      str(input$image_click)    })    output$image_hoverinfo <- renderPrint({      cat("Hover (throttled):\n")      str(input$image_hover)    })    output$image_brushinfo <- renderPrint({      cat("Brush (debounced):\n")      str(input$image_brush)    })  })}

Capture a plot as a PNG file.

Description

The PNG graphics device used is determined in the following order:

Usage

plotPNG(  func,  filename = tempfile(fileext = ".png"),  width = 400,  height = 400,  res = 72,  ...)

Arguments

func

A function that generates a plot.

filename

The name of the output file. Defaults to a temp file withextension.png.

width

Width in pixels.

height

Height in pixels.

res

Resolution in pixels per inch. This value is passed to thegraphics device. Note that this affects the resolution of PNG rendering inR; it won't change the actual ppi of the browser.

...

Arguments to be passed through to the graphics device. These canbe used to set the width, height, background color, etc.

Details

ANULL value provided towidth orheight is ignored (i.e., thedefaultwidth orheight of the graphics device is used).

Value

A path to the newly generated PNG file.


Create radio buttons

Description

Create a set of radio buttons used to select an item from a list.

Usage

radioButtons(  inputId,  label,  choices = NULL,  selected = NULL,  inline = FALSE,  width = NULL,  choiceNames = NULL,  choiceValues = NULL)

Arguments

inputId

Theinput slot that will be used to access the value.

label

Display label for the control, orNULL for no label.

choices

List of values to select from (if elements of the list arenamed then that name rather than the value is displayed to the user). Ifthis argument is provided, thenchoiceNames andchoiceValues must notbe provided, and vice-versa. The values should be strings; other types(such as logicals and numbers) will be coerced to strings.

selected

The initially selected value. If not specified, then itdefaults to the first item inchoices. To start with no items selected,usecharacter(0).

inline

IfTRUE, render the choices inline (i.e. horizontally)

width

The width of the input, e.g.'400px', or'100%';seevalidateCssUnit().

choiceNames,choiceValues

List of names and values, respectively, thatare displayed to the user in the app and correspond to the each choice (forthis reason,choiceNames andchoiceValues must have the same length).If either of these arguments is provided, then the othermust be providedandchoicesmust not be provided. The advantage of using both of theseover a named list forchoices is thatchoiceNames allows any type of UIobject to be passed through (tag objects, icons, HTML code, ...), insteadof just simple text. See Examples.

Details

If you need to represent a "None selected" state, it's possible to defaultthe radio buttons to have no options selected by usingselected = character(0). However, this is not recommended, as it gives the user no wayto return to that state once they've made a selection. Instead, considerhaving the first of your choices bec("None selected" = "").

Value

A set of radio buttons that can be added to a UI definition.

Server value

A character string containing the value of the selected button.

See Also

updateRadioButtons()

Other input elements:actionButton(),checkboxGroupInput(),checkboxInput(),dateInput(),dateRangeInput(),fileInput(),numericInput(),passwordInput(),selectInput(),sliderInput(),submitButton(),textAreaInput(),textInput(),varSelectInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  radioButtons("dist", "Distribution type:",               c("Normal" = "norm",                 "Uniform" = "unif",                 "Log-normal" = "lnorm",                 "Exponential" = "exp")),  plotOutput("distPlot"))server <- function(input, output) {  output$distPlot <- renderPlot({    dist <- switch(input$dist,                   norm = rnorm,                   unif = runif,                   lnorm = rlnorm,                   exp = rexp,                   rnorm)    hist(dist(500))  })}shinyApp(ui, server)ui <- fluidPage(  radioButtons("rb", "Choose one:",               choiceNames = list(                 icon("calendar"),                 HTML("<p style='color:red;'>Red Text</p>"),                 "Normal text"               ),               choiceValues = list(                 "icon", "html", "text"               )),  textOutput("txt"))server <- function(input, output) {  output$txt <- renderText({    paste("You chose", input$rb)  })}shinyApp(ui, server)}

Create a reactive expression

Description

Wraps a normal expression to create a reactive expression. Conceptually, areactive expression is a expression whose result will change over time.

Usage

reactive(  x,  env = parent.frame(),  quoted = FALSE,  ...,  label = NULL,  domain = getDefaultReactiveDomain(),  ..stacktraceon = TRUE)is.reactive(x)

Arguments

x

Foris.reactive(), an object to test. Forreactive(), anexpression. When passing in arlang::quo()sure withreactive(),remember to userlang::inject() to distinguish that you are passing inthe content of your quosure, not the expression of the quosure.

env

The parent environment for the reactive expression. By default,this is the calling environment, the same as when defining an ordinarynon-reactive expression. Ifx is a quosure andquoted isTRUE,thenenv is ignored.

quoted

If it isTRUE, then thequote()ed value ofxwill be used whenx is evaluated. Ifx is a quosure and youwould like to use its expression as a value forx, then you must setquoted toTRUE.

...

Not used.

label

A label for the reactive expression, useful for debugging.

domain

Seedomains.

..stacktraceon

Advanced use only. For stack manipulation purposes; seestacktrace().

Details

Reactive expressions are expressions that can read reactive values and callother reactive expressions. Whenever a reactive value changes, any reactiveexpressions that depended on it are marked as "invalidated" and willautomatically re-execute if necessary. If a reactive expression is marked asinvalidated, any other reactive expressions that recently called it are alsomarked as invalidated. In this way, invalidations ripple through theexpressions that depend on each other.

See theShiny tutorial formore information about reactive expressions.

Value

a function, wrapped in a S3 class "reactive"

Examples

library(rlang)values <- reactiveValues(A=1)reactiveB <- reactive({  values$A + 1})# View the values from the R console with isolate()isolate(reactiveB())# 2# To store expressions for later conversion to reactive, use quote()myquo <- rlang::quo(values$A + 2)# Unexpected value! Sending a quosure directly will not work as expected.reactiveC <- reactive(myquo)# We'd hope for `3`, but instead we get the quosure that was supplied.isolate(reactiveC())# Instead, the quosure should be `rlang::inject()`edreactiveD <- rlang::inject(reactive(!!myquo))isolate(reactiveD())# 3# (Legacy) Can use quoted expressionsexpr <- quote({ values$A + 3 })reactiveE <- reactive(expr, quoted = TRUE)isolate(reactiveE())# 4

Activate reactivity in the console

Description

This is an experimental feature that allows you to enable reactivityat the console, for the purposes of experimentation and learning.

Usage

reactiveConsole(enabled)

Arguments

enabled

Turn console reactivity on or off?

Examples

reactiveConsole(TRUE)x <- reactiveVal(10)y <- observe({  message("The value of x is ", x())})x(20)x(30)reactiveConsole(FALSE)

Reactive file reader

Description

Given a file path and read function, returns a reactive data source for thecontents of the file.

Usage

reactiveFileReader(intervalMillis, session, filePath, readFunc, ...)

Arguments

intervalMillis

Approximate number of milliseconds to wait betweenchecks of the file's last modified time. This can be a numeric value, or afunction that returns a numeric value.

session

The user session to associate this file reader with, orNULL if none. If non-null, the reader will automatically stop whenthe session ends.

filePath

The file path to poll against and to pass toreadFunc.This can either be a single-element character vector, or a function thatreturns one.

readFunc

The function to use to read the file; must expect the firstargument to be the file path to read. The return value of this function isused as the value of the reactive file reader.

...

Any additional arguments to pass toreadFunc whenever it isinvoked.

Details

reactiveFileReader works by periodically checking the file's lastmodified time; if it has changed, then the file is re-read and any reactivedependents are invalidated.

TheintervalMillis,filePath, andreadFunc functionswill each be executed in a reactive context; therefore, they may readreactive values and reactive expressions.

Value

A reactive expression that returns the contents of the file, andautomatically invalidates when the file changes on disk (as determined bylast modified time).

See Also

reactivePoll()

Examples

## Not run: # Per-session reactive file readerfunction(input, output, session) {  fileData <- reactiveFileReader(1000, session, 'data.csv', read.csv)  output$data <- renderTable({    fileData()  })}# Cross-session reactive file reader. In this example, all sessions share# the same reader, so read.csv only gets executed once no matter how many# user sessions are connected.fileData <- reactiveFileReader(1000, NULL, 'data.csv', read.csv)function(input, output, session) {  output$data <- renderTable({    fileData()  })}## End(Not run)

Reactive polling

Description

Used to create a reactive data source, which works by periodically polling anon-reactive data source.

Usage

reactivePoll(intervalMillis, session, checkFunc, valueFunc)

Arguments

intervalMillis

Approximate number of milliseconds to wait betweencalls tocheckFunc. This can be either a numeric value, or afunction that returns a numeric value.

session

The user session to associate this file reader with, orNULL if none. If non-null, the reader will automatically stop whenthe session ends.

checkFunc

A relatively cheap function whose values over time will betested for equality; inequality indicates that the underlying value haschanged and needs to be invalidated and re-read usingvalueFunc. SeeDetails.

valueFunc

A function that calculates the underlying value. SeeDetails.

Details

reactivePoll works by pairing a relatively cheap "check" function witha more expensive value retrieval function. The check function will beexecuted periodically and should always return a consistent value until thedata changes. When the check function returns a different value, then thevalue retrieval function will be used to re-populate the data.

Note that the check function doesn't returnTRUE orFALSE toindicate whether the underlying data has changed. Rather, the check functionindicates change by returning a different value from the previous time it wascalled.

For example,reactivePoll is used to implementreactiveFileReader by pairing a check function that simply returns thelast modified timestamp of a file, and a value retrieval function thatactually reads the contents of the file.

As another example, one might read a relational database table reactively byusing a check function that does⁠SELECT MAX(timestamp) FROM table⁠ anda value retrieval function that does⁠SELECT * FROM table⁠.

TheintervalMillis,checkFunc, andvalueFunc functionswill be executed in a reactive context; therefore, they may read reactivevalues and reactive expressions.

Value

A reactive expression that returns the result ofvalueFunc,and invalidates whencheckFunc changes.

See Also

reactiveFileReader()

Examples

function(input, output, session) {  data <- reactivePoll(1000, session,    # This function returns the time that log_file was last modified    checkFunc = function() {      if (file.exists(log_file))        file.info(log_file)$mtime[1]      else        ""    },    # This function returns the content of log_file    valueFunc = function() {      read.csv(log_file)    }  )  output$dataTable <- renderTable({    data()  })}

Timer

Description

Creates a reactive timer with the given interval. A reactive timer is like areactive value, except reactive values are triggered when they are set, whilereactive timers are triggered simply by the passage of time.

Usage

reactiveTimer(intervalMs = 1000, session = getDefaultReactiveDomain())

Arguments

intervalMs

How often to fire, in milliseconds

session

A session object. This is needed to cancel any scheduledinvalidations after a user has ended the session. IfNULL, thenthis invalidation will not be tied to any session, and so it will stilloccur.

Details

Reactive expressions and observers that want to beinvalidated by the timer need to call the timer function thatreactiveTimer returns, even if the current time value is not actuallyneeded.

SeeinvalidateLater() as a safer and simpler alternative.

Value

A no-parameter function that can be called from a reactive context,in order to cause that context to be invalidated the next time the timerinterval elapses. Calling the returned function also happens to yield thecurrent time (as inbase::Sys.time()).

See Also

invalidateLater()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  sliderInput("n", "Number of observations", 2, 1000, 500),  plotOutput("plot"))server <- function(input, output) {  # Anything that calls autoInvalidate will automatically invalidate  # every 2 seconds.  autoInvalidate <- reactiveTimer(2000)  observe({    # Invalidate and re-execute this reactive expression every time the    # timer fires.    autoInvalidate()    # Do something each time this is invalidated.    # The isolate() makes this observer _not_ get invalidated and re-executed    # when input$n changes.    print(paste("The value of input$n is", isolate(input$n)))  })  # Generate a new histogram each time the timer fires, but not when  # input$n changes.  output$plot <- renderPlot({    autoInvalidate()    hist(rnorm(isolate(input$n)))  })}shinyApp(ui, server)}

Create a (single) reactive value

Description

ThereactiveVal function is used to construct a "reactive value"object. This is an object used for reading and writing a value, like avariable, but with special capabilities for reactive programming. When youread the value out of a reactiveVal object, the calling reactive expressiontakes a dependency, and when you change the value, it notifies any reactivesthat previously depended on that value.

Usage

reactiveVal(value = NULL, label = NULL)

Arguments

value

An optional initial value.

label

An optional label, for debugging purposes (seereactlog()). If missing, a label will be automaticallycreated.

Details

reactiveVal is very similar toreactiveValues(), exceptthat the former is for a single reactive value (like a variable), whereas thelatter lets you conveniently use multiple reactive values by name (like anamed list of variables). For a one-off reactive value, it's more natural tousereactiveVal. See the Examples section for an illustration.

Value

A function. Call the function with no arguments to (reactively) readthe value; call the function with a single argument to set the value.

Examples

## Not run: # Create the object by calling reactiveValr <- reactiveVal()# Set the value by calling with an argumentr(10)# Read the value by calling without argumentsr()## End(Not run)## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  actionButton("minus", "-1"),  actionButton("plus", "+1"),  br(),  textOutput("value"))# The comments below show the equivalent logic using reactiveValues()server <- function(input, output, session) {  value <- reactiveVal(0)       # rv <- reactiveValues(value = 0)  observeEvent(input$minus, {    newValue <- value() - 1     # newValue <- rv$value - 1    value(newValue)             # rv$value <- newValue  })  observeEvent(input$plus, {    newValue <- value() + 1     # newValue <- rv$value + 1    value(newValue)             # rv$value <- newValue  })  output$value <- renderText({    value()                     # rv$value  })}shinyApp(ui, server)}

Create an object for storing reactive values

Description

This function returns an object for storing reactive values. It is similar toa list, but with special capabilities for reactive programming. When you reada value from it, the calling reactive expression takes a reactive dependencyon that value, and when you write to it, it notifies any reactive functionsthat depend on that value. Note that values taken from the reactiveValuesobject are reactive, but the reactiveValues object itself is not.

Usage

reactiveValues(...)

Arguments

...

Objects that will be added to the reactivevalues object. All ofthese objects must be named.

See Also

isolate() andis.reactivevalues().

Examples

# Create the object with no valuesvalues <- reactiveValues()# Assign values to 'a' and 'b'values$a <- 3values[['b']] <- 4## Not run: # From within a reactive context, you can access values with:values$avalues[['a']]## End(Not run)# If not in a reactive context (e.g., at the console), you can use isolate()# to retrieve the value:isolate(values$a)isolate(values[['a']])# Set values upon creationvalues <- reactiveValues(a = 1, b = 2)isolate(values$a)

Convert a reactivevalues object to a list

Description

This function does something similar to what you might want or expectbase::as.list() to do. The difference is that the calling context will takedependencies on every object in thereactivevalues object. To avoid takingdependencies on all the objects, you can wrap the call withisolate().

Usage

reactiveValuesToList(x, all.names = FALSE)

Arguments

x

Areactivevalues object.

all.names

IfTRUE, include objects with a leading dot. IfFALSE(the default) don't include those objects.

Examples

values <- reactiveValues(a = 1)## Not run: reactiveValuesToList(values)## End(Not run)# To get the objects without taking dependencies on them, use isolate().# isolate() can also be used when calling from outside a reactive context (e.g.# at the console)isolate(reactiveValuesToList(values))

Reactive Log Visualizer

Description

Provides an interactive browser-based tool for visualizing reactivedependencies and execution in your application.

Usage

reactlog()reactlogShow(time = TRUE)reactlogReset()reactlogAddMark(session = getDefaultReactiveDomain())

Arguments

time

A boolean that specifies whether or not to display thetime that each reactive takes to calculate a result.

session

The Shiny session to assign the mark to. Defaults to thecurrent session.

Details

To use the reactive log visualizer, start with a fresh R session andrun the commandreactlog::reactlog_enable(); then launch yourapplication in the usual way (e.g. usingrunApp()). Atany time you can hit Ctrl+F3 (or for Mac users, Command+F3) in yourweb browser to launch the reactive log visualization.

The reactive log visualization only includes reactive activity upuntil the time the report was loaded. If you want to see more recentactivity, refresh the browser.

Note that Shiny does not distinguish between reactive dependenciesthat "belong" to one Shiny user session versus another, so thevisualization will include all reactive activity that has taken placein the process, not just for a particular application or session.

As an alternative to pressing Ctrl/Command+F3–for example, if youare using reactives outside of the context of a Shinyapplication–you can run thereactlogShow function, which willgenerate the reactive log visualization as a static HTML file andlaunch it in your default browser. In this case, refreshing yourbrowser will not load new activity into the report; you will need tocallreactlogShow() explicitly.

For security and performance reasons, do not enableoptions(shiny.reactlog=TRUE) (orreactlog::reactlog_enable()) inproduction environments. When the option is enabled, it's possiblefor any user of your app to see at least some of the source code ofyour reactive expressions and observers. In addition, reactlogshould be considered a memory leak as it will constantly grow andwill never reset until the R session is restarted.

Functions


Objects exported from other packages

Description

These objects are imported from other packages. Follow the linksbelow to see their documentation.

fastmap

is.key_missing,key_missing

htmltools

a,br,code,div,em,h1,h2,h3,h4,h5,h6,hr,HTML,htmlTemplate,img,includeCSS,includeHTML,includeMarkdown,includeScript,includeText,is.singleton,p,pre,singleton,span,strong,suppressDependencies,tag,tagAppendAttributes,tagAppendChild,tagAppendChildren,tagGetAttribute,tagHasAttribute,tagList,tags,tagSetChildren,validateCssUnit,withTags


Register an Input Handler

Description

Adds an input handler for data of this type. When called, Shiny will use thefunction provided to refine the data passed back from the client (after beingdeserialized by jsonlite) before making it available in theinput variableof theserver.R file.

Usage

registerInputHandler(type, fun, force = FALSE)

Arguments

type

The type for which the handler should be added — should be asingle-element character vector.

fun

The handler function. This is the function that will be used toparse the data delivered from the client before it is available in theinput variable. The function will be called with the following threeparameters:

  1. The value of this input as provided by theclient, deserialized using jsonlite.

  2. Theshinysession in which theinput exists.

  3. The name of the input.

force

IfTRUE, will overwrite any existing handler without warning.IfFALSE, will throw an error if this class already has a handlerdefined.

Details

This function will register the handler for the duration of the R process(unless Shiny is explicitly reloaded). For that reason, thetype usedshould be very specific to this package to minimize the risk of collidingwith another Shiny package which might use this data type name. We recommendthe format of "packageName.widgetName". It should be called from thepackage's.onLoad() function.

Currently Shiny registers the following handlers:shiny.matrix,shiny.number, andshiny.date.

Thetype of a custom Shiny Input widget will be deduced using thegetType() JavaScript function on the registered Shiny inputBinding.

See Also

removeInputHandler()applyInputHandlers()

Examples

## Not run: # Register an input handler which rounds a input number to the nearest integer# In a package, this should be called from the .onLoad function.registerInputHandler("mypackage.validint", function(x, shinysession, name) {  if (is.null(x)) return(NA)  round(x)})## On the Javascript side, the associated input binding must have a corresponding getType method:# getType: function(el) {#   return "mypackage.validint";# }## End(Not run)

Register a theme dependency

Description

This function registers a function that returns anhtmltools::htmlDependency() or list of such objects. Ifsession$setCurrentTheme() is called, the function will be re-executed, andthe resulting html dependency will be sent to the client.

Usage

registerThemeDependency(func)

Arguments

func

A function that takes one argument,theme (which is asass::sass_layer() object), and returns an htmlDependency object, or listof them.

Details

Note thatfunc shouldnot be an anonymous function, or a function whichis defined within the calling function. This is so that,registerThemeDependency() is called multiple times with the function, ittries to deduplicate them


Deregister an Input Handler

Description

Removes an Input Handler. Rather than using the previously specified handlerfor data of this type, the default jsonlite serialization will be used.

Usage

removeInputHandler(type)

Arguments

type

The type for which handlers should be removed.

Value

The handler previously associated with thistype, if oneexisted. Otherwise,NULL.

See Also

registerInputHandler()


Plot output with cached images

Description

Renders a reactive plot, with plot images cached to disk. As of Shiny 1.6.0,this is a shortcut for usingbindCache() withrenderPlot().

Usage

renderCachedPlot(  expr,  cacheKeyExpr,  sizePolicy = sizeGrowthRatio(width = 400, height = 400, growthRate = 1.2),  res = 72,  cache = "app",  ...,  alt = "Plot object",  outputArgs = list(),  width = NULL,  height = NULL)

Arguments

expr

An expression that generates a plot.

cacheKeyExpr

An expression that returns a cache key. This key shouldbe a unique identifier for a plot: the assumption is that if the cache keyis the same, then the plot will be the same.

sizePolicy

A function that takes two arguments,width andheight, and returns a list withwidth andheight. Thepurpose is to round the actual pixel dimensions from the browser to someother dimensions, so that this will not generate and cache images of everypossible pixel dimension. SeesizeGrowthRatio() for moreinformation on the default sizing policy.

res

The resolution of the PNG, in pixels per inch.

cache

The scope of the cache, or a cache object. This can be"app"(the default),"session", or a cache object like acachem::cache_disk(). See the Cache Scoping section for more information.

...

Arguments to be passed through toplotPNG().These can be used to set the width, height, background color, etc.

alt

Alternate text for the HTML⁠<img>⁠ tag if it cannot be displayedor viewed (i.e., the user uses a screen reader). In addition to a characterstring, the value may be a reactive expression (or a function referencingreactive values) that returns a character string. If the value isNA (thedefault), thenggplot2::get_alt_text() is used to extract alt text fromggplot objects; for other plots,NA results in alt text of "Plot object".NULL or"" is not recommended because those should be limited todecorative images.

outputArgs

A list of arguments to be passed through to the implicitcall toplotOutput() whenrenderPlot is used in aninteractive R Markdown document.

width,height

not used. They are specified via the argumentsizePolicy.

Details

expr is an expression that generates a plot, similar to that inrenderPlot. Unlike withrenderPlot, this expression does nottake reactive dependencies. It is re-executed only when the cache keychanges.

cacheKeyExpr is an expression which, when evaluated, returns an objectwhich will be serialized and hashed using therlang::hash()function to generate a string that will be used as a cache key. This key isused to identify the contents of the plot: if the cache key is the same as aprevious time, it assumes that the plot is the same and can be retrieved fromthe cache.

ThiscacheKeyExpr is reactive, and so it will be re-evaluated when anyupstream reactives are invalidated. This will also trigger re-execution ofthe plotting expression,expr.

The key should consist of "normal" R objects, like vectors and lists. Listsshould in turn contain other normal R objects. If the key containsenvironments, external pointers, or reference objects — or even if it hassuch objects attached as attributes — then it is possible that it willchange unpredictably even when you do not expect it to. Additionally, becausethe entire key is serialized and hashed, if it contains a very large object— a large data set, for example — there may be a noticeable performancepenalty.

If you face these issues with the cache key, you can work around them byextracting out the important parts of the objects, and/or by converting themto normal R objects before returning them. Your expression could evenserialize and hash that information in an efficient way and return a string,which will in turn be hashed (very quickly) by therlang::hash() function.

Internally, the result fromcacheKeyExpr is combined with the name ofthe output (if you assign it tooutput$plot1, it will be combinedwith"plot1") to form the actual key that is used. As a result, evenif there are multiple plots that have the samecacheKeyExpr, theywill not have cache key collisions.

Interactive plots

renderCachedPlot can be used to create interactive plots. SeeplotOutput() for more information and examples.

See Also

SeerenderPlot() for the regular, non-cached version of thisfunction. It can be used withbindCache() to get the same effect asrenderCachedPlot(). For more about configuring caches, seecachem::cache_mem() andcachem::cache_disk().

Examples

## Only run examples in interactive R sessionsif (interactive()) {# A basic example that uses the default app-scoped memory cache.# The cache will be shared among all simultaneous users of the application.shinyApp(  fluidPage(    sidebarLayout(      sidebarPanel(        sliderInput("n", "Number of points", 4, 32, value = 8, step = 4)      ),      mainPanel(plotOutput("plot"))    )  ),  function(input, output, session) {    output$plot <- renderCachedPlot({        Sys.sleep(2)  # Add an artificial delay        seqn <- seq_len(input$n)        plot(mtcars$wt[seqn], mtcars$mpg[seqn],             xlim = range(mtcars$wt), ylim = range(mtcars$mpg))      },      cacheKeyExpr = { list(input$n) }    )  })# An example uses a data object shared across sessions. mydata() is part of# the cache key, so when its value changes, plots that were previously# stored in the cache will no longer be used (unless mydata() changes back# to its previous value).mydata <- reactiveVal(data.frame(x = rnorm(400), y = rnorm(400)))ui <- fluidPage(  sidebarLayout(    sidebarPanel(      sliderInput("n", "Number of points", 50, 400, 100, step = 50),      actionButton("newdata", "New data")    ),    mainPanel(      plotOutput("plot")    )  ))server <- function(input, output, session) {  observeEvent(input$newdata, {    mydata(data.frame(x = rnorm(400), y = rnorm(400)))  })  output$plot <- renderCachedPlot(    {      Sys.sleep(2)      d <- mydata()      seqn <- seq_len(input$n)      plot(d$x[seqn], d$y[seqn], xlim = range(d$x), ylim = range(d$y))    },    cacheKeyExpr = { list(input$n, mydata()) },  )}shinyApp(ui, server)# A basic application with two plots, where each plot in each session has# a separate cache.shinyApp(  fluidPage(    sidebarLayout(      sidebarPanel(        sliderInput("n", "Number of points", 4, 32, value = 8, step = 4)      ),      mainPanel(        plotOutput("plot1"),        plotOutput("plot2")      )    )  ),  function(input, output, session) {    output$plot1 <- renderCachedPlot({        Sys.sleep(2)  # Add an artificial delay        seqn <- seq_len(input$n)        plot(mtcars$wt[seqn], mtcars$mpg[seqn],             xlim = range(mtcars$wt), ylim = range(mtcars$mpg))      },      cacheKeyExpr = { list(input$n) },      cache = cachem::cache_mem()    )    output$plot2 <- renderCachedPlot({        Sys.sleep(2)  # Add an artificial delay        seqn <- seq_len(input$n)        plot(mtcars$wt[seqn], mtcars$mpg[seqn],             xlim = range(mtcars$wt), ylim = range(mtcars$mpg))      },      cacheKeyExpr = { list(input$n) },      cache = cachem::cache_mem()    )  })}## Not run: # At the top of app.R, this set the application-scoped cache to be a memory# cache that is 20 MB in size, and where cached objects expire after one# hour.shinyOptions(cache = cachem::cache_mem(max_size = 20e6, max_age = 3600))# At the top of app.R, this set the application-scoped cache to be a disk# cache that can be shared among multiple concurrent R processes, and is# deleted when the system reboots.shinyOptions(cache = cachem::cache_disk(file.path(dirname(tempdir()), "myapp-cache")))# At the top of app.R, this set the application-scoped cache to be a disk# cache that can be shared among multiple concurrent R processes, and# persists on disk across reboots.shinyOptions(cache = cachem::cache_disk("./myapp-cache"))# At the top of the server function, this set the session-scoped cache to be# a memory cache that is 5 MB in size.server <- function(input, output, session) {  shinyOptions(cache = cachem::cache_mem(max_size = 5e6))  output$plot <- renderCachedPlot(    ...,    cache = "session"  )}## End(Not run)

Image file output

Description

Renders a reactive image that is suitable for assigning to anoutputslot.

Usage

renderImage(  expr,  env = parent.frame(),  quoted = FALSE,  deleteFile,  outputArgs = list())

Arguments

expr

An expression that returns a list.

env

The parent environment for the reactive expression. By default,this is the calling environment, the same as when defining an ordinarynon-reactive expression. Ifexpr is a quosure andquoted isTRUE,thenenv is ignored.

quoted

If it isTRUE, then thequote()ed value ofexprwill be used whenexpr is evaluated. Ifexpr is a quosure and youwould like to use its expression as a value forexpr, then you must setquoted toTRUE.

deleteFile

Should the file infunc()$src be deleted afterit is sent to the client browser? Generally speaking, if the image is atemp file generated withinfunc, then this should beTRUE;if the image is not a temp file, this should beFALSE. (For backwardcompatibility reasons, if this argument is missing, a warning will beemitted, and if the file is in the temp directory it will be deleted. Inthe future, this warning will become an error.)

outputArgs

A list of arguments to be passed through to the implicitcall toimageOutput() whenrenderImage is used in aninteractive R Markdown document.

Details

The expressionexpr must return a list containing the attributes fortheimg object on the client web page. For the image to display,properly, the list must have at least one entry,src, which is thepath to the image file. It may also useful to have acontentTypeentry specifying the MIME type of the image. If one is not provided,renderImage will try to autodetect the type, based on the fileextension.

Other elements such aswidth,height,class, andalt, can also be added to the list, and they will be used asattributes in theimg object.

The corresponding HTML output tag should bediv orimg and havethe CSS class nameshiny-image-output.

See Also

Examples

## Only run examples in interactive R sessionsif (interactive()) {options(device.ask.default = FALSE)ui <- fluidPage(  sliderInput("n", "Number of observations", 2, 1000, 500),  plotOutput("plot1"),  plotOutput("plot2"),  plotOutput("plot3"))server <- function(input, output, session) {  # A plot of fixed size  output$plot1 <- renderImage({    # A temp file to save the output. It will be deleted after renderImage    # sends it, because deleteFile=TRUE.    outfile <- tempfile(fileext='.png')    # Generate a png    png(outfile, width=400, height=400)    hist(rnorm(input$n))    dev.off()    # Return a list    list(src = outfile,         alt = "This is alternate text")  }, deleteFile = TRUE)  # A dynamically-sized plot  output$plot2 <- renderImage({    # Read plot2's width and height. These are reactive values, so this    # expression will re-run whenever these values change.    width  <- session$clientData$output_plot2_width    height <- session$clientData$output_plot2_height    # A temp file to save the output.    outfile <- tempfile(fileext='.png')    png(outfile, width=width, height=height)    hist(rnorm(input$n))    dev.off()    # Return a list containing the filename    list(src = outfile,         width = width,         height = height,         alt = "This is alternate text")  }, deleteFile = TRUE)  # Send a pre-rendered image, and don't delete the image after sending it  # NOTE: For this example to work, it would require files in a subdirectory  # named images/  output$plot3 <- renderImage({    # When input$n is 1, filename is ./images/image1.jpeg    filename <- normalizePath(file.path('./images',                              paste('image', input$n, '.jpeg', sep='')))    # Return a list containing the filename    list(src = filename)  }, deleteFile = FALSE)}shinyApp(ui, server)}

Plot Output

Description

Renders a reactive plot that is suitable for assigning to anoutputslot.

Usage

renderPlot(  expr,  width = "auto",  height = "auto",  res = 72,  ...,  alt = NA,  env = parent.frame(),  quoted = FALSE,  execOnResize = FALSE,  outputArgs = list())

Arguments

expr

An expression that generates a plot.

width,height

Height and width can be specified in three ways:

  • "auto", the default, uses the size specified byplotOutput()(i.e. theoffsetWidth/'offsetHeight“ of the HTML element bound tothis plot.)

  • An integer, defining the width/height in pixels.

  • A function that returns the width/height in pixels (or"auto").The function is executed in a reactive context so that you can refer toreactive values and expression to make the width/height reactive.

When rendering an inline plot, you must provide numeric values (in pixels)to bothwidth andheight.

res

Resolution of resulting plot, in pixels per inch. This value ispassed toplotPNG(). Note that this affects the resolution of PNGrendering in R; it won't change the actual ppi of the browser.

...

Arguments to be passed through toplotPNG().These can be used to set the width, height, background color, etc.

alt

Alternate text for the HTML⁠<img>⁠ tag if it cannot be displayedor viewed (i.e., the user uses a screen reader). In addition to a characterstring, the value may be a reactive expression (or a function referencingreactive values) that returns a character string. If the value isNA (thedefault), thenggplot2::get_alt_text() is used to extract alt text fromggplot objects; for other plots,NA results in alt text of "Plot object".NULL or"" is not recommended because those should be limited todecorative images.

env

The parent environment for the reactive expression. By default,this is the calling environment, the same as when defining an ordinarynon-reactive expression. Ifexpr is a quosure andquoted isTRUE,thenenv is ignored.

quoted

If it isTRUE, then thequote()ed value ofexprwill be used whenexpr is evaluated. Ifexpr is a quosure and youwould like to use its expression as a value forexpr, then you must setquoted toTRUE.

execOnResize

IfFALSE (the default), then when a plot isresized, Shiny willreplay the plot drawing commands withgrDevices::replayPlot() instead of re-executingexpr.This can result in faster plot redrawing, but there may be rare cases whereit is undesirable. If you encounter problems when resizing a plot, you canhave Shiny re-execute the code on resize by setting this toTRUE.

outputArgs

A list of arguments to be passed through to the implicitcall toplotOutput() whenrenderPlot is used in aninteractive R Markdown document.

Details

The corresponding HTML output tag should bediv orimg and havethe CSS class nameshiny-plot-output.

Interactive plots

With ggplot2 graphics, the code inrenderPlot should return a ggplotobject; if instead the code prints the ggplot2 object with something likeprint(p), then the coordinates for interactive graphics will not beproperly scaled to the data space.

SeeplotOutput() for more information about interactive plots.

See Also

For the corresponding client-side output function, and exampleusage, seeplotOutput(). For more details on how the plots aregenerated, and how to control the output, seeplotPNG().renderCachedPlot() offers a way to cache generated plots toexpedite the rendering of identical plots.


Text Output

Description

renderPrint() prints the result ofexpr, whilerenderText() pastes ittogether into a single string.renderPrint() is equivalent toprint();renderText() is equivalent tocat(). Both functions capture all otherprinted output generated while evaluatingexpr.

renderPrint() is usually paired withverbatimTextOutput();renderText() is usually paired withtextOutput().

Usage

renderPrint(  expr,  env = parent.frame(),  quoted = FALSE,  width = getOption("width"),  outputArgs = list())renderText(  expr,  env = parent.frame(),  quoted = FALSE,  outputArgs = list(),  sep = " ")

Arguments

expr

An expression to evaluate.

env

The parent environment for the reactive expression. By default,this is the calling environment, the same as when defining an ordinarynon-reactive expression. Ifexpr is a quosure andquoted isTRUE,thenenv is ignored.

quoted

If it isTRUE, then thequote()ed value ofexprwill be used whenexpr is evaluated. Ifexpr is a quosure and youwould like to use its expression as a value forexpr, then you must setquoted toTRUE.

width

Width of printed output.

outputArgs

A list of arguments to be passed through to the implicitcall toverbatimTextOutput() ortextOutput() when the functions areused in an interactive RMarkdown document.

sep

A separator passed tocat to be appended after eachelement.

Details

The corresponding HTML output tag can be anything (thoughpre isrecommended if you need a monospace font and whitespace preserved) and shouldhave the CSS class nameshiny-text-output.

Value

ForrenderPrint(), note the given expression returnsNULL thenNULLwill actually be visible in the output. To display nothing, make yourfunction returninvisible().

See Also

outputOptions()

Examples

isolate({# renderPrint captures any print output, converts it to a string, and# returns itvisFun <- renderPrint({ "foo" })visFun()# '[1] "foo"'invisFun <- renderPrint({ invisible("foo") })invisFun()# ''multiprintFun <- renderPrint({  print("foo");  "bar"})multiprintFun()# '[1] "foo"\n[1] "bar"'nullFun <- renderPrint({ NULL })nullFun()# 'NULL'invisNullFun <- renderPrint({ invisible(NULL) })invisNullFun()# ''vecFun <- renderPrint({ 1:5 })vecFun()# '[1] 1 2 3 4 5'# Contrast with renderText, which takes the value returned from the function# and uses cat() to convert it to a stringvisFun <- renderText({ "foo" })visFun()# 'foo'invisFun <- renderText({ invisible("foo") })invisFun()# 'foo'multiprintFun <- renderText({  print("foo");  "bar"})multiprintFun()# 'bar'nullFun <- renderText({ NULL })nullFun()# ''invisNullFun <- renderText({ invisible(NULL) })invisNullFun()# ''vecFun <- renderText({ 1:5 })vecFun()# '1 2 3 4 5'})

UI Output

Description

Renders reactive HTML using the Shiny UI library.

Usage

renderUI(expr, env = parent.frame(), quoted = FALSE, outputArgs = list())

Arguments

expr

An expression that returns a Shiny tag object,HTML(),or a list of such objects.

env

The parent environment for the reactive expression. By default,this is the calling environment, the same as when defining an ordinarynon-reactive expression. Ifexpr is a quosure andquoted isTRUE,thenenv is ignored.

quoted

If it isTRUE, then thequote()ed value ofexprwill be used whenexpr is evaluated. Ifexpr is a quosure and youwould like to use its expression as a value forexpr, then you must setquoted toTRUE.

outputArgs

A list of arguments to be passed through to the implicitcall touiOutput() whenrenderUI is used in aninteractive R Markdown document.

Details

The corresponding HTML output tag should bediv and have the CSS classnameshiny-html-output (or useuiOutput()).

See Also

uiOutput(),outputOptions()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  uiOutput("moreControls"))server <- function(input, output) {  output$moreControls <- renderUI({    tagList(      sliderInput("n", "N", 1, 1000, 500),      textInput("label", "Label")    )  })}shinyApp(ui, server)}

Make a random number generator repeatable

Description

Given a function that generates random data, returns a wrapped version ofthat function that always uses the same seed when called. The seed to use canbe passed in explicitly if desired; otherwise, a random number is used.

Usage

repeatable(rngfunc, seed = stats::runif(1, 0, .Machine$integer.max))

Arguments

rngfunc

The function that is affected by the R session's seed.

seed

The seed to set every time the resulting function is called.

Value

A repeatable version of the function that was passed in.

Note

When called, the returned function attempts to preserve the R session'scurrent seed by snapshotting and restoringbase::.Random.seed().

Examples

rnormA <- repeatable(rnorm)rnormB <- repeatable(rnorm)rnormA(3)  # [1]  1.8285879 -0.7468041 -0.4639111rnormA(3)  # [1]  1.8285879 -0.7468041 -0.4639111rnormA(5)  # [1]  1.8285879 -0.7468041 -0.4639111 -1.6510126 -1.4686924rnormB(5)  # [1] -0.7946034  0.2568374 -0.6567597  1.2451387 -0.8375699

Check for required values

Description

Ensure that values are available ("truthy") before proceedingwith a calculation or action. If any of the given values is not truthy, theoperation is stopped by raising a "silent" exception (not logged by Shiny,nor displayed in the Shiny app's UI).

Usage

req(..., cancelOutput = FALSE)

Arguments

...

Values to check for truthiness.

cancelOutput

IfTRUE and an output is being evaluated, stopprocessing as usual but instead of clearing the output, leave it inwhatever state it happens to be in. If"progress", do the same asTRUE,but also keep the output in recalculating state; this is intended for caseswhen an in-progress calculation will not be completed in this reactiveflush cycle, but is still expected to provide a result in the future.

Details

Thereq function was designed to be used in one of two ways. The firstis to call it like a statement (ignoring its return value) before attemptingoperations using the required values:

rv <- reactiveValues(state = FALSE)r <- reactive({  req(input$a, input$b, rv$state)  # Code that uses input$a, input$b, and/or rv$state...})

In this example, ifr() is called and any ofinput$a,input$b, andrv$state areNULL,FALSE,"",etc., then thereq call will trigger an error that propagates all theway up to whatever render block or observer is executing.

The second is to use it to wrap an expression that must be truthy:

output$plot <- renderPlot({  if (req(input$plotType) == "histogram") {    hist(dataset())  } else if (input$plotType == "scatter") {    qplot(dataset(), aes(x = x, y = y))  }})

In this example,req(input$plotType) first checks thatinput$plotType is truthy, and if so, returns it. This is a convenientway to check for a value "inline" with its first use.

Value

The first value that was passed in.

Usingreq(FALSE)

You can usereq(FALSE) (i.e. no condition) if you've already performedall the checks you needed to by that point and just want to stop the reactivechain now. There is no advantage to this, except perhaps ease of readabilityif you have a complicated condition to check for (or perhaps if you'd like todivide your condition into nestedif statements).

UsingcancelOutput = TRUE

Whenreq(..., cancelOutput = TRUE) is used, the "silent" exception isalso raised, but it is treated slightly differently if one or more outputs arecurrently being evaluated. In those cases, the reactive chain does not proceedor update, but the output(s) are left is whatever state they happen to be in(whatever was their last valid state).

Note that this is always going to be the case ifthis is used inside an output context (e.g.output$txt <- ...). It mayor may not be the case if it is used inside a non-output context (e.g.reactive(),observe() orobserveEvent())— depending on whether or not there is anoutput$... that is triggeredas a result of those calls. See the examples below for concrete scenarios.

Examples

## Only run examples in interactive R sessionsif (interactive()) {  ui <- fluidPage(    textInput('data', 'Enter a dataset from the "datasets" package', 'cars'),    p('(E.g. "cars", "mtcars", "pressure", "faithful")'), hr(),    tableOutput('tbl')  )  server <- function(input, output) {    output$tbl <- renderTable({      ## to require that the user types something, use: `req(input$data)`      ## but better: require that input$data is valid and leave the last      ## valid table up      req(exists(input$data, "package:datasets", inherits = FALSE),          cancelOutput = TRUE)      head(get(input$data, "package:datasets", inherits = FALSE))    })  }  shinyApp(ui, server)}

Restore an input value

Description

This restores an input value from the current restore context. It should becalled early on inside of input functions (liketextInput()).

Usage

restoreInput(id, default)

Arguments

id

Name of the input value to restore.

default

A default value to use, if there's no value to restore.


Run Shiny Application

Description

Runs a Shiny application. This function normally does not return; interrupt Rto stop the application (usually by pressing Ctrl+C or Esc).

Usage

runApp(  appDir = getwd(),  port = getOption("shiny.port"),  launch.browser = getOption("shiny.launch.browser", interactive()),  host = getOption("shiny.host", "127.0.0.1"),  workerId = "",  quiet = FALSE,  display.mode = c("auto", "normal", "showcase"),  test.mode = getOption("shiny.testmode", FALSE))

Arguments

appDir

The application to run. Should be one of the following:

  • A directory containingserver.R, plus, eitherui.R orawww directory that contains the fileindex.html.

  • A directory containingapp.R.

  • An.R file containing a Shiny application, ending with anexpression that produces a Shiny app object.

  • A list withui andserver components.

  • A Shiny app object created byshinyApp().

port

The TCP port that the application should listen on. If theport is not specified, and theshiny.port option is set (withoptions(shiny.port = XX)), then that port will be used. Otherwise,use a random port between 3000:8000, excluding ports that are blockedby Google Chrome for being considered unsafe: 3659, 4045, 5060,5061, 6000, 6566, 6665:6669 and 6697. Up to twenty randomports will be tried.

launch.browser

If true, the system's default web browser will belaunched automatically after the app is started. Defaults to true ininteractive sessions only. The value of this parameter can also be afunction to call with the application's URL.

host

The IPv4 address that the application should listen on. Defaultsto theshiny.host option, if set, or"127.0.0.1" if not. SeeDetails.

workerId

Can generally be ignored. Exists to help some editions ofShiny Server Pro route requests to the correct process.

quiet

Should Shiny status messages be shown? Defaults to FALSE.

display.mode

The mode in which to display the application. If set tothe value"showcase", shows application code and metadata from aDESCRIPTION file in the application directory alongside theapplication. If set to"normal", displays the application normally.Defaults to"auto", which displays the application in the mode givenin itsDESCRIPTION file, if any.

test.mode

Should the application be launched in test mode? This isonly used for recording or running automated tests. Defaults to theshiny.testmode option, or FALSE if the option is not set.

Details

The host parameter was introduced in Shiny 0.9.0. Its default value of"127.0.0.1" means that, contrary to previous versions of Shiny, onlythe current machine can access locally hosted Shiny apps. To allow otherclients to connect, use the value"0.0.0.0" instead (which was thevalue that was hard-coded into Shiny in 0.8.0 and earlier).

Examples

## Not run: # Start app in the current working directoryrunApp()# Start app in a subdirectory called myapprunApp("myapp")## End(Not run)## Only run this example in interactive R sessionsif (interactive()) {  options(device.ask.default = FALSE)  # Apps can be run without a server.r and ui.r file  runApp(list(    ui = bootstrapPage(      numericInput('n', 'Number of obs', 100),      plotOutput('plot')    ),    server = function(input, output) {      output$plot <- renderPlot({ hist(runif(input$n)) })    }  ))  # Running a Shiny app object  app <- shinyApp(    ui = bootstrapPage(      numericInput('n', 'Number of obs', 100),      plotOutput('plot')    ),    server = function(input, output) {      output$plot <- renderPlot({ hist(runif(input$n)) })    }  )  runApp(app)}

Run Shiny Example Applications

Description

Launch Shiny example applications, and optionally, your system's web browser.

Usage

runExample(  example = NA,  port = getOption("shiny.port"),  launch.browser = getOption("shiny.launch.browser", interactive()),  host = getOption("shiny.host", "127.0.0.1"),  display.mode = c("auto", "normal", "showcase"),  package = "shiny")

Arguments

example

The name of the example to run, orNA (the default) tolist the available examples.

port

The TCP port that the application should listen on. If theport is not specified, and theshiny.port option is set (withoptions(shiny.port = XX)), then that port will be used. Otherwise,use a random port between 3000:8000, excluding ports that are blockedby Google Chrome for being considered unsafe: 3659, 4045, 5060,5061, 6000, 6566, 6665:6669 and 6697. Up to twenty randomports will be tried.

launch.browser

If true, the system's default web browser will belaunched automatically after the app is started. Defaults to true ininteractive sessions only.

host

The IPv4 address that the application should listen on. Defaultsto theshiny.host option, if set, or"127.0.0.1" if not.

display.mode

The mode in which to display the example. Defaults to"auto", which uses the value ofDisplayMode in the example'sDESCRIPTION file. Set to"showcase" to show the app code anddescription with the running app, or"normal" to see the example withoutcode or commentary.

package

The package in which to find the example (defaults to"shiny").

To provide examples in your package, store examples in theinst/examples-shiny directory of your package. Each example should bein its own subdirectory and should be runnable whenrunApp() is calledon the subdirectory. Example apps can include aDESCRIPTION file and aREADME.md file to provide metadata and commentary about the example. Seethe article onDisplay Modeson the Shiny website for more information.

Examples

## Only run this example in interactive R sessionsif (interactive()) {  # List all available examples  runExample()  # Run one of the examples  runExample("01_hello")  # Print the directory containing the code for all examples  system.file("examples", package="shiny")}

Run a gadget

Description

Similar torunApp, but handlesinput$cancel automatically, andif running in RStudio, defaults to viewing the app in the Viewer pane.

Usage

runGadget(  app,  server = NULL,  port = getOption("shiny.port"),  viewer = paneViewer(),  stopOnCancel = TRUE)

Arguments

app

Either a Shiny app object as created byshinyApp() et al, or, a UI object.

server

Ignored ifapp is a Shiny app object; otherwise, passedalong toshinyApp (i.e.shinyApp(ui = app, server = server)).

port

SeerunApp().

viewer

Specify where the gadget should be displayed–viewer pane,dialog window, or external browser–by passing in a call to one of theviewer() functions.

stopOnCancel

IfTRUE (the default), then anobserveEventis automatically created that handlesinput$cancel by callingstopApp() with an error. PassFALSE if you want to handleinput$cancel yourself.

Value

The value returned by the gadget.

Examples

## Not run: library(shiny)ui <- fillPage(...)server <- function(input, output, session) {  ...}# Either pass ui/server as separate arguments...runGadget(ui, server)# ...or as a single app objectrunGadget(shinyApp(ui, server))## End(Not run)

Runs the tests associated with this Shiny app

Description

Sources the.R files in the top-level of⁠tests/⁠ much like⁠R CMD check⁠.These files are typically simple runners for tests nested in otherdirectories under⁠tests/⁠.

Usage

runTests(appDir = ".", filter = NULL, assert = TRUE, envir = globalenv())

Arguments

appDir

The base directory for the application.

filter

If notNULL, only tests with file names matching this regularexpression will be executed. Matching is performed on the file nameincluding the extension.

assert

Logical value which determines if an error should be thrown if any error is captured.

envir

Parent testing environment in which to base the individual testing environments.

Details

Historically,shinytestrecommended placing tests at the top-level of the⁠tests/⁠ directory.This older folder structure is not supported by runTests.Please seeshinyAppTemplate() for more details.

Value

A data frame classed with the supplemental class"shiny_runtests".The data frame has the following columns:

NameTypeMeaning
filecharacter(1) File name of the runner script in⁠tests/⁠ that was sourced.
passlogical(1) Whether or not the runner script signaled an error when sourced.
result any orNA The return value of the runner

Run a Shiny application from a URL

Description

runUrl() downloads and launches a Shiny application that is hosted ata downloadable URL. The Shiny application must be saved in a .zip, .tar, or.tar.gz file. The Shiny application files must be contained in the rootdirectory or a subdirectory in the archive. For example, the files might bemyapp/server.r andmyapp/ui.r. The functionsrunGitHub()andrunGist() are based onrunUrl(), using URL's from GitHub(https://github.com) and GitHub gists (https://gist.github.com),respectively.

Usage

runUrl(url, filetype = NULL, subdir = NULL, destdir = NULL, ...)runGist(gist, destdir = NULL, ...)runGitHub(  repo,  username = getOption("github.user"),  ref = "HEAD",  subdir = NULL,  destdir = NULL,  ...)

Arguments

url

URL of the application.

filetype

The file type (".zip",".tar", or".tar.gz". Defaults to the file extension taken from the url.

subdir

A subdirectory in the repository that contains the app. Bydefault, this function will run an app from the top level of the repo, butyou can use a path such as"inst/shinyapp".

destdir

Directory to store the downloaded application files. IfNULL(the default), the application files will be stored in a temporary directoryand removed when the app exits

...

Other arguments to be passed torunApp(), such asport andlaunch.browser.

gist

The identifier of the gist. For example, if the gist ishttps://gist.github.com/jcheng5/3239667, then3239667,'3239667', and'https://gist.github.com/jcheng5/3239667' areall valid values.

repo

Name of the repository.

username

GitHub username. Ifrepo is of the form"username/repo",username will be taken fromrepo.

ref

Desired git reference. Could be a commit, tag, or branch name.Defaults to"HEAD", which means the default branch on GitHub, typically"main" or"master".

Examples

## Only run this example in interactive R sessionsif (interactive()) {  runUrl('https://github.com/rstudio/shiny_example/archive/main.tar.gz')  # Can run an app from a subdirectory in the archive  runUrl("https://github.com/rstudio/shiny_example/archive/main.zip",    subdir = "inst/shinyapp/")}## Only run this example in interactive R sessionsif (interactive()) {  runGist(3239667)  runGist("https://gist.github.com/jcheng5/3239667")  # Old URL format without username  runGist("https://gist.github.com/3239667")}## Only run this example in interactive R sessionsif (interactive()) {  runGitHub("shiny_example", "rstudio")  # or runGitHub("rstudio/shiny_example")  # Can run an app from a subdirectory in the repo  runGitHub("shiny_example", "rstudio", subdir = "inst/shinyapp/")}

Declare an error safe for the user to see

Description

This should be used when you want to let the user see an errormessage even if the default is to sanitize all errors. If you have anerrore and callstop(safeError(e)), then Shiny willignore the value ofgetOption("shiny.sanitize.errors") and alwaysdisplay the error in the app itself.

Usage

safeError(error)

Arguments

error

Either an "error" object or a "character" object (string).In the latter case, the string will become the message of the errorreturned bysafeError.

Details

An error generated bysafeError has priority over allother Shiny errors. This can be dangerous. For example, if you have setoptions(shiny.sanitize.errors = TRUE), then by default all errormessages are omitted in the app, and replaced by a generic error message.However, this does not apply tosafeError: whatever you passthrougherror will be displayed to the user. So, this should onlybe used when you are sure that your error message does not contain anysensitive information. In those situations,safeError can makeyour users' lives much easier by giving them a hint as to where theerror occurred.

Value

An "error" object

See Also

shiny-options()

Examples

## Only run examples in interactive R sessionsif (interactive()) {# uncomment the desired line to experiment with shiny.sanitize.errors# options(shiny.sanitize.errors = TRUE)# options(shiny.sanitize.errors = FALSE)# Define UIui <- fluidPage(  textInput('number', 'Enter your favorite number from 1 to 10', '5'),  textOutput('normalError'),  textOutput('safeError'))# Server logicserver <- function(input, output) {  output$normalError <- renderText({    number <- input$number    if (number %in% 1:10) {      return(paste('You chose', number, '!'))    } else {      stop(        paste(number, 'is not a number between 1 and 10')      )    }  })  output$safeError <- renderText({    number <- input$number    if (number %in% 1:10) {      return(paste('You chose', number, '!'))    } else {      stop(safeError(        paste(number, 'is not a number between 1 and 10')      ))    }  })}# Complete app with UI and server componentsshinyApp(ui, server)}

Create a select list input control

Description

Create a select list that can be used to choose a single or multiple itemsfrom a list of values.

Usage

selectInput(  inputId,  label,  choices,  selected = NULL,  multiple = FALSE,  selectize = TRUE,  width = NULL,  size = NULL)selectizeInput(inputId, ..., options = NULL, width = NULL)

Arguments

inputId

Theinput slot that will be used to access the value.

label

Display label for the control, orNULL for no label.

choices

List of values to select from. If elements of the list arenamed, then that name — rather than the value — is displayed to theuser. It's also possible to group related inputs by providing a named listwhose elements are (either named or unnamed) lists, vectors, or factors. Inthis case, the outermost names will be used as the group labels (leveragingthe⁠<optgroup>⁠ HTML tag) for the elements in the respective sublist. Seethe example section for a small demo of this feature.

selected

The initially selected value (or multiple values ifmultiple = TRUE). If not specified then defaults to the first value forsingle-select lists and no values for multiple select lists.

multiple

Is selection of multiple items allowed?

selectize

Whether to useselectize.js or not.

width

The width of the input, e.g.'400px', or'100%';seevalidateCssUnit().

size

Number of items to show in the selection box; a larger numberwill result in a taller box. Not compatible withselectize=TRUE.Normally, whenmultiple=FALSE, a select input will be a drop-down list,but whensize is set, it will be a box instead.

...

Arguments passed toselectInput().

options

A list of options. See the documentation ofselectize.js(https://selectize.dev/docs/usage)for possible options (character option values insidebase::I() willbe treated as literal JavaScript code; seerenderDataTable()for details).

Details

By default,selectInput() andselectizeInput() use the JavaScript libraryselectize.js (https://selectize.dev/) instead ofthe basic select input element. To use the standard HTML select inputelement, useselectInput() withselectize=FALSE.

In selectize mode, if the first element inchoices has a value of"", itsname will be treated as a placeholder prompt. For example:selectInput("letter", "Letter", c("Choose one" = "", LETTERS))

Performance note:selectInput() andselectizeInput() can slow downsignificantly when thousands of choices are used; with legacy browsers likeInternet Explorer, the user interface may hang for many seconds. For largenumbers of choices, Shiny offers a "server-side selectize" option thatmassively improves performance and efficiency; seethis selectize articleon the Shiny Dev Center for details.

Value

A select list control that can be added to a UI definition.

Server value

A vector of character strings, usually of length1, with the value of the selected items. Whenmultiple=TRUE andnothing is selected, this value will beNULL.

Note

The selectize input created fromselectizeInput() allowsdeletion of the selected option even in a single select input, which willreturn an empty string as its value. This is the default behavior ofselectize.js. However, the selectize input created fromselectInput(..., selectize = TRUE) will ignore the empty stringvalue when it is a single choice input and the empty string is not in thechoices argument. This is to keep compatibility withselectInput(..., selectize = FALSE).

See Also

updateSelectInput()varSelectInput()

Other input elements:actionButton(),checkboxGroupInput(),checkboxInput(),dateInput(),dateRangeInput(),fileInput(),numericInput(),passwordInput(),radioButtons(),sliderInput(),submitButton(),textAreaInput(),textInput(),varSelectInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {# basic exampleshinyApp(  ui = fluidPage(    selectInput("variable", "Variable:",                c("Cylinders" = "cyl",                  "Transmission" = "am",                  "Gears" = "gear")),    tableOutput("data")  ),  server = function(input, output) {    output$data <- renderTable({      mtcars[, c("mpg", input$variable), drop = FALSE]    }, rownames = TRUE)  })# demoing group support in the `choices` argshinyApp(  ui = fluidPage(    selectInput("state", "Choose a state:",      list(`East Coast` = list("NY", "NJ", "CT"),           `West Coast` = list("WA", "OR", "CA"),           `Midwest` = list("MN", "WI", "IA"))    ),    textOutput("result")  ),  server = function(input, output) {    output$result <- renderText({      paste("You chose", input$state)    })  })}

Collect information about the Shiny Server environment

Description

This function returns the information about the current Shiny Server, such asits version, and whether it is the open source edition or professionaledition. If the app is not served through the Shiny Server, this functionjust returnslist(shinyServer = FALSE).

Usage

serverInfo()

Details

This function will only return meaningful data when using Shiny Serverversion 1.2.2 or later.

Value

A list of the Shiny Server information.


Session object

Description

Shiny server functions can optionally includesession as a parameter(e.g.⁠function(input, output, session)⁠). The session object is anenvironment that can be used to access information and functionalityrelating to the session. The following list describes the items availablein the environment; they can be accessed using the$ operator (forexample,session$clientData$url_search).

Value

allowReconnect(value)

Ifvalue isTRUE and run in a hosting environment (ShinyServer or Connect) with reconnections enabled, then when the session endsdue to the network connection closing, the client will attempt toreconnect to the server. If a reconnection is successful, the browser willsend all the current input values to the new session on the server, andthe server will recalculate any outputs and send them back to the client.Ifvalue isFALSE, reconnections will be disabled (this isthe default state). If"force", then the client browser will alwaysattempt to reconnect. The only reason to use"force" is for testingon a local connection (without Shiny Server or Connect).

clientData

AreactiveValues() object that contains information about the client.

  • pixelratio reports the "device pixel ratio" from the web browser,or 1 if none is reported. The value is 2 for Apple Retina displays.

  • singletons - for internal use

  • url_protocol,url_hostname,url_port,url_pathname,url_search,url_hash_initialandurl_hash can be used to get the components of the URLthat was requested by the browser to load the Shiny app page.These values are from the browser's perspective, so neither HTTPproxies nor Shiny Server will affect these values. Theurl_search value may be used withparseQueryString()to access query string parameters.

clientData also contains information about each output.output_outputId_width andoutput_outputId_heightgive the dimensions (usingoffsetWidth andoffsetHeight) ofthe DOM element that is bound tooutputId, andoutput_outputId_hidden is a logical that indicates whetherthe element is hidden. These values may beNULL if the output isnot bound.

input

The session'sinput object (the same as is passed into the Shinyserver function as an argument).

isClosed()

A function that returnsTRUE if the client hasdisconnected.

ns(id)

Server-side version ofns <- NS(id). If bare IDs need to beexplicitly namespaced for the current module,session$ns("name")will return the fully-qualified ID.

onEnded(callback)

Synonym foronSessionEnded.

onFlush(func,once=TRUE)

Registers a function to be called before the next time (ifonce=TRUE)or every time (ifonce=FALSE) Shiny flushes the reactive system.Returns a function that can be called with no arguments to cancel theregistration.

onFlushed(func,once=TRUE)

Registers a function to be called after the next time (ifonce=TRUE)or every time (ifonce=FALSE) Shiny flushes the reactive system.Returns a function that can be called with no arguments to cancel theregistration.

onSessionEnded(callback)

Registers a function to be called after the client has disconnected.Returns a function that can be called with no arguments to cancel theregistration.

output

The session'soutput object (the same as is passed into the Shinyserver function as an argument).

reactlog

For internal use.

registerDataObj(name,data,filterFunc)

Publishes any R object as a URL endpoint that is unique to this session.name must be a single element character vector; it will be usedto form part of the URL.filterFunc must be a function that takestwo arguments:data (the value that was passed intoregisterDataObj) andreq (an environment that implementsthe Rook specification for HTTP requests).filterFunc will becalled with these values whenever an HTTP request is made to the URLendpoint. The return value offilterFunc should be a Rook-styleresponse.

reload()

The equivalent of hitting the browser's Reload button. Only works if thesession is actually connected.

request

An environment that implements theRook specification forHTTP requests. This is the request that was used to initiate the websocketconnection (as opposed to the request that downloaded the web page for theapp).

userData

An environment for app authors and module/package authors to store whateversession-specific data they want.

user

User's log-in information. Useful for identifying users on hosted platformssuch as RStudio Connect and Shiny Server.

groups

Theuser's relevant group information. Useful for determining whatprivileges the user should or shouldn't have.

resetBrush(brushId)

Resets/clears the brush with the givenbrushId, if it exists onanyimageOutput orplotOutput in the app.

sendCustomMessage(type,message)

Sends a custom message to the web page.type must be asingle-element character vector giving the type of message, whilemessage can be any jsonlite-encodable value. Custom messageshave no meaning to Shiny itself; they are used solely to convey informationto custom JavaScript logic in the browser. You can do this by addingJavaScript code to the browser that callsShiny.addCustomMessageHandler(type, function(message){...})as the page loads; the function you provide toaddCustomMessageHandler will be invoked each timesendCustomMessage is called on the server.

sendBinaryMessage(type,message)

Similar tosendCustomMessage, but the message must be a raw vectorand the registration method on the client isShiny.addBinaryMessageHandler(type, function(message){...}). Themessage argument on the client will be aDataView.

sendInputMessage(inputId,message)

Sends a message to an input on the session's client web page; if the inputis present and bound on the page at the time the message is received, thenthe input binding object'sreceiveMessage(el, message) method willbe called.sendInputMessage should generally not be called directlyfrom Shiny apps, but through friendlier wrapper functions likeupdateTextInput().

setBookmarkExclude(names)

Set input names to be excluded from bookmarking.

getBookmarkExclude()

Returns the set of input names to be excluded from bookmarking.

onBookmark(fun)

Registers a function that will be called just before bookmarking state.

onBookmarked(fun)

Registers a function that will be called just after bookmarking state.

onRestore(fun)

Registers a function that will be called when a session is restored, beforeall other reactives, observers, and render functions are run.

onRestored(fun)

Registers a function that will be called when a session is restored, afterall other reactives, observers, and render functions are run.

doBookmark()

Do bookmarking and invoke the onBookmark and onBookmarked callback functions.

exportTestValues()

Registers expressions for export in test mode, available at the testsnapshot URL.

getTestSnapshotUrl(input=TRUE,output=TRUE,export=TRUE,format="json")

Returns a URL for the test snapshots. Only has an effect when theshiny.testmode option is set to TRUE. For the input, output, andexport arguments, TRUE means to return all of these values. It is alsopossible to specify by name which values to return by providing acharacter vector, as ininput=c("x", "y"). The format can be"rds" or "json".

setCurrentTheme(theme)

Sets the currentbootstrapLib() theme, which updates the value ofgetCurrentTheme(), invalidatessession$getCurrentTheme(), and callsfunction(s) registered withregisterThemeDependency() with providedtheme. If those function calls returnhtmltools::htmlDependency()s withstylesheets, then those stylesheets are "refreshed" (i.e., the newstylesheets are inserted on the page and the old ones are disabled andremoved).

getCurrentTheme()

A reactive read of the currentbootstrapLib() theme.


Exclude inputs from bookmarking

Description

This function tells Shiny which inputs should be excluded from bookmarking.It should be called from inside the application's server function.

Usage

setBookmarkExclude(names = character(0), session = getDefaultReactiveDomain())

Arguments

names

A character vector containing names of inputs to exclude frombookmarking.

session

A shiny session object.

Details

This function can also be called from a module's server function, in whichcase it will exclude inputs with the specified names, from that module. Itwill not affect inputs from other modules or from the top level of the Shinyapplication.

See Also

enableBookmarking() for examples.


Add a function for serializing an input before bookmarking application state

Description

Add a function for serializing an input before bookmarking application state

Usage

setSerializer(inputId, fun, session = getDefaultReactiveDomain())

Arguments

inputId

Name of the input value.

fun

A function that takes the input value and returns a modifiedvalue. The returned value will be used for the test snapshot.

session

A Shiny session object.


Shiny App object

Description

Internal methods for theshiny.appobj S3 class.

Usage

as.shiny.appobj(x)## S3 method for class 'shiny.appobj'as.shiny.appobj(x)## S3 method for class 'list'as.shiny.appobj(x)## S3 method for class 'character'as.shiny.appobj(x)is.shiny.appobj(x)## S3 method for class 'shiny.appobj'print(x, ...)## S3 method for class 'shiny.appobj'as.tags(x, ...)

Arguments

x

Object to convert to a Shiny app.

...

Ignored.


Create a Shiny app object

Description

These functions create Shiny app objects from either an explicit UI/serverpair (shinyApp), or by passing the path of a directory that contains aShiny app (shinyAppDir).

Usage

shinyApp(  ui,  server,  onStart = NULL,  options = list(),  uiPattern = "/",  enableBookmarking = NULL)shinyAppDir(appDir, options = list())shinyAppFile(appFile, options = list())

Arguments

ui

The UI definition of the app (for example, a call tofluidPage() with nested controls).

If bookmarking is enabled (seeenableBookmarking), this must bea single argument function that returns the UI definition.

server

A function with three parameters:input,output, andsession. The function is called once for each session ensuring that eachapp is independent.

onStart

A function that will be called before the app is actually run.This is only needed forshinyAppObj, since in theshinyAppDircase, aglobal.R file can be used for this purpose.

options

Named options that should be passed to therunApp call(these can be any of the following: "port", "launch.browser", "host", "quiet","display.mode" and "test.mode"). You can also specifywidth andheight parameters which provide a hint to the embedding environmentabout the ideal height/width for the app.

uiPattern

A regular expression that will be applied to eachGETrequest to determine whether theui should be used to handle therequest. Note that the entire request path must match the regularexpression in order for the match to be considered successful.

enableBookmarking

Can be one of"url","server", or"disable". The default value,NULL, will respect the setting fromany previous calls toenableBookmarking(). SeeenableBookmarking()for more information on bookmarking your app.

appDir

Path to directory that contains a Shiny app (i.e. a server.Rfile and either ui.R or www/index.html)

appFile

Path to a .R file containing a Shiny application

Details

Normally when this function is used at the R console, the Shiny app object isautomatically passed to theprint() function, which runs the app. Ifthis is called in the middle of a function, the value will not be passed toprint() and the app will not be run. To make the app run, pass the appobject toprint() orrunApp().

Value

An object that represents the app. Printing the object or passing ittorunApp() will run the app.

Examples

## Only run this example in interactive R sessionsif (interactive()) {  options(device.ask.default = FALSE)  shinyApp(    ui = fluidPage(      numericInput("n", "n", 1),      plotOutput("plot")    ),    server = function(input, output) {      output$plot <- renderPlot( plot(head(cars, input$n)) )    }  )  shinyAppDir(system.file("examples/01_hello", package="shiny"))  # The object can be passed to runApp()  app <- shinyApp(    ui = fluidPage(      numericInput("n", "n", 1),      plotOutput("plot")    ),    server = function(input, output) {      output$plot <- renderPlot( plot(head(cars, input$n)) )    }  )  runApp(app)}

Generate a Shiny application from a template

Description

This function populates a directory with files for a Shiny application.

Usage

shinyAppTemplate(path = NULL, examples = "default", dryrun = FALSE)

Arguments

path

Path to create new shiny application template.

examples

Either one of "default", "ask", "all", or any combination of"app", "rdir", "module", and "tests". In aninteractive session, "default" falls back to "ask"; in a non-interactivesession, "default" falls back to "all". With "ask", this function willprompt the user to select which template items will be added to the new appdirectory. With "all", all template items will be added to the appdirectory.

dryrun

IfTRUE, don't actually write any files; just print out whichfiles would be written.

Details

In an interactive R session, this function will, by default, prompt the userto select which components to add to the application. Choices are

1: All2: app.R              : Main application file3: R/example.R        : Helper file with R code4: R/example-module.R : Example module5: tests/testthat/    : Tests using the testthat and shinytest2 package

If option 1 is selected, the full example application including thefollowing files and directories is created:

appdir/|- app.R|- R|   |- example-module.R|   `- example.R`- tests    |- testthat.R    `- testthat        |- setup-shinytest2.R        |- test-examplemodule.R        |- test-server.R        |- test-shinytest2.R        `- test-sort.R

Some notes about these files:


Print message for deprecated functions in Shiny

Description

To disable these messages, useoptions(shiny.deprecation.messages=FALSE).

Usage

shinyDeprecated(  version,  what,  with = NULL,  details = NULL,  type = c("deprecated", "superseded"))

Arguments

version

Shiny version when the function was deprecated

what

Function with possible arguments

with

Possible function with arguments that should be used instead

details

Additional information to be added after a new line to the displayed message


Define Server Functionality

Description

[Superseded]

Defines the server-side logic of the Shiny application. This generallyinvolves creating functions that map user inputs to various kinds of output.In older versions of Shiny, it was necessary to callshinyServer() intheserver.R file, but this is no longer required as of Shiny 0.10.Now theserver.R file may simply return the appropriate serverfunction (as the last expression in the code), without callingshinyServer().

CallshinyServer from your application'sserver.Rfile, passing in a "server function" that provides the server-side logic ofyour application.

The server function will be called when each client (web browser) first loadsthe Shiny application's page. It must take aninput and anoutput parameter. Any return value will be ignored. It also takes anoptionalsession parameter, which is used when greater control isneeded.

See thetutorial for moreon how to write a server function.

Usage

shinyServer(func)

Arguments

func

The server function for this application. See the details sectionfor more information.

Examples

## Not run: # A very simple Shiny app that takes a message from the user# and outputs an uppercase version of it.shinyServer(function(input, output, session) {  output$uppercase <- renderText({    toupper(input$message)  })})# It is also possible for a server.R file to simply return the function,# without calling shinyServer().# For example, the server.R file could contain just the following:function(input, output, session) {  output$uppercase <- renderText({    toupper(input$message)  })}## End(Not run)

Create a Shiny UI handler

Description

[Superseded]

Historically this function was used in ui.R files to register a userinterface with Shiny. It is no longer required as of Shiny 0.10; simplyensure that the last expression to be returned from ui.R is a user interface.This function is kept for backwards compatibility with older applications. Itreturns the value that is passed to it.

Usage

shinyUI(ui)

Arguments

ui

A user interface definition

Value

The user interface definition, without modifications or side effects.


Display a modal dialog for bookmarking

Description

This is a wrapper function forurlModal() that is automaticallycalled if an application is bookmarked but no otheronBookmark()callback was set. It displays a modal dialog with the bookmark URL, alongwith a subtitle that is appropriate for the type of bookmarking used ("url"or "server").

Usage

showBookmarkUrlModal(url)

Arguments

url

A URL to show in the modal dialog.


Show or remove a modal dialog

Description

This causes a modal dialog to be displayed in the client browser, and istypically used withmodalDialog().

Usage

showModal(ui, session = getDefaultReactiveDomain())removeModal(session = getDefaultReactiveDomain())

Arguments

ui

UI content to show in the modal.

session

Thesession object passed to function given toshinyServer.

See Also

modalDialog() for examples.


Show or remove a notification

Description

These functions show and remove notifications in a Shiny application.

Usage

showNotification(  ui,  action = NULL,  duration = 5,  closeButton = TRUE,  id = NULL,  type = c("default", "message", "warning", "error"),  session = getDefaultReactiveDomain())removeNotification(id, session = getDefaultReactiveDomain())

Arguments

ui

Content of message.

action

Message content that represents an action. For example, thiscould be a link that the user can click on. This is separate fromuiso customized layouts can handle the main notification content separatelyfrom action content.

duration

Number of seconds to display the message before itdisappears. UseNULL to make the message not automaticallydisappear.

closeButton

IfTRUE, display a button which will make thenotification disappear when clicked. IfFALSE do not display.

id

A unique identifier for the notification.

id is optional forshowNotification(): Shiny will automatically createone if needed. If you do supply it, Shiny will update an existingnotification if it exists, otherwise it will create a new one.

id is required forremoveNotification().

type

A string which controls the color of the notification. One of"default" (gray), "message" (blue), "warning" (yellow), or "error" (red).

session

Session object to send notification to.

Value

An ID for the notification.

Examples

## Only run examples in interactive R sessionsif (interactive()) {# Show a message when button is clickedshinyApp(  ui = fluidPage(    actionButton("show", "Show")  ),  server = function(input, output) {    observeEvent(input$show, {      showNotification("Message text",        action = a(href = "#", "Reload page")      )    })  })# App with show and remove buttonsshinyApp(  ui = fluidPage(    actionButton("show", "Show"),    actionButton("remove", "Remove")  ),  server = function(input, output) {    # A queue of notification IDs    ids <- character(0)    # A counter    n <- 0    observeEvent(input$show, {      # Save the ID for removal later      id <- showNotification(paste("Message", n), duration = NULL)      ids <<- c(ids, id)      n <<- n + 1    })    observeEvent(input$remove, {      if (length(ids) > 0)        removeNotification(ids[1])      ids <<- ids[-1]    })  })}

Dynamically hide/show a tabPanel

Description

Dynamically hide or show atabPanel() (or anavbarMenu())from an existingtabsetPanel(),navlistPanel() ornavbarPage().

Usage

showTab(inputId, target, select = FALSE, session = getDefaultReactiveDomain())hideTab(inputId, target, session = getDefaultReactiveDomain())

Arguments

inputId

Theid of thetabsetPanel (ornavlistPanel ornavbarPage) in which to findtarget.

target

Thevalue of thetabPanel to behidden/shown. See Details if you want to hide/show an entirenavbarMenu instead.

select

Shouldtarget be selected upon being shown?

session

The shiny session within which to call this function.

Details

FornavbarPage, you can hide/show conventionaltabPanels (whether at the top level or nested inside anavbarMenu), as well as an entirenavbarMenu().For the latter case,target should be themenuName thatyou gave yournavbarMenu when you first created it (by default,this is equal to the value of thetitle argument).

See Also

insertTab()

Examples

## Only run this example in interactive R sessionsif (interactive()) {ui <- navbarPage("Navbar page", id = "tabs",  tabPanel("Home",    actionButton("hideTab", "Hide 'Foo' tab"),    actionButton("showTab", "Show 'Foo' tab"),    actionButton("hideMenu", "Hide 'More' navbarMenu"),    actionButton("showMenu", "Show 'More' navbarMenu")  ),  tabPanel("Foo", "This is the foo tab"),  tabPanel("Bar", "This is the bar tab"),  navbarMenu("More",    tabPanel("Table", "Table page"),    tabPanel("About", "About page"),    "------",    "Even more!",    tabPanel("Email", "Email page")  ))server <- function(input, output, session) {  observeEvent(input$hideTab, {    hideTab(inputId = "tabs", target = "Foo")  })  observeEvent(input$showTab, {    showTab(inputId = "tabs", target = "Foo")  })  observeEvent(input$hideMenu, {    hideTab(inputId = "tabs", target = "More")  })  observeEvent(input$showMenu, {    showTab(inputId = "tabs", target = "More")  })}shinyApp(ui, server)}

Layout a sidebar and main area

Description

Create a layout (sidebarLayout()) with a sidebar (sidebarPanel()) andmain area (mainPanel()). The sidebar is displayed with a distinctbackground color and typically contains input controls. The mainarea occupies 2/3 of the horizontal width and typically contains outputs.

Usage

sidebarLayout(  sidebarPanel,  mainPanel,  position = c("left", "right"),  fluid = TRUE)sidebarPanel(..., width = 4)mainPanel(..., width = 8)

Arguments

sidebarPanel

ThesidebarPanel() containing input controls.

mainPanel

ThemainPanel() containing outputs.

position

The position of the sidebar relative to the main area ("left"or "right").

fluid

TRUE to use fluid layout;FALSE to use fixedlayout.

...

Output elements to include in the sidebar/main panel.

width

The width of the sidebar and main panel. By default, thesidebar takes up 1/3 of the width, and the main panel 2/3. The totalwidth must be 12 or less.

See Also

Other layout functions:fillPage(),fixedPage(),flowLayout(),fluidPage(),navbarPage(),splitLayout(),verticalLayout()

Examples

## Only run examples in interactive R sessionsif (interactive()) {options(device.ask.default = FALSE)# Define UIui <- fluidPage(  # Application title  titlePanel("Hello Shiny!"),  sidebarLayout(    # Sidebar with a slider input    sidebarPanel(      sliderInput("obs",                  "Number of observations:",                  min = 0,                  max = 1000,                  value = 500)    ),    # Show a plot of the generated distribution    mainPanel(      plotOutput("distPlot")    )  ))# Server logicserver <- function(input, output) {  output$distPlot <- renderPlot({    hist(rnorm(input$obs))  })}# Complete app with UI and server componentsshinyApp(ui, server)}

Create a sizing function that grows at a given ratio

Description

Returns a function which takes a two-element vector representing an inputwidth and height, and returns a two-element vector of width and height. Thepossible widths are the base width times the growthRate to any integer power.For example, with a base width of 500 and growth rate of 1.25, the possiblewidths include 320, 400, 500, 625, 782, and so on, both smaller and larger.Sizes are rounded up to the next pixel. Heights are computed the same way aswidths.

Usage

sizeGrowthRatio(width = 400, height = 400, growthRate = 1.2)

Arguments

width,height

Base width and height.

growthRate

Growth rate multiplier.

See Also

This is to be used withrenderCachedPlot().

Examples

f <- sizeGrowthRatio(500, 500, 1.25)f(c(400, 400))f(c(500, 500))f(c(530, 550))f(c(625, 700))

Slider Input Widget

Description

Constructs a slider widget to select a number, date, or date-time from arange.

Usage

sliderInput(  inputId,  label,  min,  max,  value,  step = NULL,  round = FALSE,  ticks = TRUE,  animate = FALSE,  width = NULL,  sep = ",",  pre = NULL,  post = NULL,  timeFormat = NULL,  timezone = NULL,  dragRange = TRUE)animationOptions(  interval = 1000,  loop = FALSE,  playButton = NULL,  pauseButton = NULL)

Arguments

inputId

Theinput slot that will be used to access the value.

label

Display label for the control, orNULL for no label.

min,max

The minimum and maximum values (inclusive) that can beselected.

value

The initial value of the slider, either a number, a date(class Date), or a date-time (class POSIXt). A length one vector willcreate a regular slider; a length two vector will create a double-endedrange slider. Must lie betweenmin andmax.

step

Specifies the interval between each selectable value on theslider. EitherNULL, the default, which uses a heuristic to determine thestep size or a single number. If the values are dates,step is in days;if the values are date-times,step is in seconds.

round

TRUE to round all values to the nearest integer;FALSE if no rounding is desired; or an integer to round to thatnumber of digits (for example, 1 will round to the nearest 10, and -2 willround to the nearest .01). Any rounding will be applied after snapping tothe nearest step.

ticks

FALSE to hide tick marks,TRUE to show themaccording to some simple heuristics.

animate

TRUE to show simple animation controls with defaultsettings;FALSE not to; or a custom settings list, such as thosecreated usinganimationOptions().

width

The width of the input, e.g.'400px', or'100%';seevalidateCssUnit().

sep

Separator between thousands places in numbers.

pre

A prefix string to put in front of the value.

post

A suffix string to put after the value.

timeFormat

Only used if the values are Date or POSIXt objects. A timeformat string, to be passed to the Javascript strftime library. Seehttps://github.com/samsonjs/strftime for more details. The allowedformat specifications are very similar, but not identical, to those for R'sbase::strftime() function. For Dates, the default is"%F"(like"2015-07-01"), and for POSIXt, the default is"%F %T"(like"2015-07-01 15:32:10").

timezone

Only used if the values are POSIXt objects. A stringspecifying the time zone offset for the displayed times, in the format"+HHMM" or"-HHMM". IfNULL (the default), times willbe displayed in the browser's time zone. The value"+0000" willresult in UTC time.

dragRange

This option is used only if it is a range slider (with twovalues). IfTRUE (the default), the range can be dragged. In otherwords, the min and max can be dragged together. IfFALSE, the rangecannot be dragged.

interval

The interval, in milliseconds, between each animation step.

loop

TRUE to automatically restart the animation when itreaches the end.

playButton

Specifies the appearance of the play button. Valid valuesare a one-element character vector (for a simple text label), an HTML tagor list of tags (usingtag() and friends), or raw HTML (usingHTML()).

pauseButton

Similar toplayButton, but for the pause button.

Server value

A number, date, or date-time (depending on the class ofvalue), orin the case of slider range, a vector of two numbers/dates/date-times.

See Also

updateSliderInput()

Other input elements:actionButton(),checkboxGroupInput(),checkboxInput(),dateInput(),dateRangeInput(),fileInput(),numericInput(),passwordInput(),radioButtons(),selectInput(),submitButton(),textAreaInput(),textInput(),varSelectInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {options(device.ask.default = FALSE)ui <- fluidPage(  sliderInput("obs", "Number of observations:",    min = 0, max = 1000, value = 500  ),  plotOutput("distPlot"))# Server logicserver <- function(input, output) {  output$distPlot <- renderPlot({    hist(rnorm(input$obs))  })}# Complete app with UI and server componentsshinyApp(ui, server)}

Mark an output to be excluded from test snapshots

Description

Mark an output to be excluded from test snapshots

Usage

snapshotExclude(x)

Arguments

x

A reactive which will be assigned to an output.


Add a function for preprocessing an input before taking a test snapshot

Description

Add a function for preprocessing an input before taking a test snapshot

Usage

snapshotPreprocessInput(inputId, fun, session = getDefaultReactiveDomain())

Arguments

inputId

Name of the input value.

fun

A function that takes the input value and returns a modifiedvalue. The returned value will be used for the test snapshot.

session

A Shiny session object.


Add a function for preprocessing an output before taking a test snapshot

Description

Add a function for preprocessing an output before taking a test snapshot

Usage

snapshotPreprocessOutput(x, fun)

Arguments

x

A reactive which will be assigned to an output.

fun

A function that takes the output value as an input and returns amodified value. The returned value will be used for the test snapshot.


Split layout

Description

Lays out elements horizontally, dividing the available horizontal space intoequal parts (by default).

Usage

splitLayout(..., cellWidths = NULL, cellArgs = list())

Arguments

...

Unnamed arguments will become child elements of the layout. Namedarguments will become HTML attributes on the outermost tag.

cellWidths

Character or numeric vector indicating the widths of theindividual cells. Recycling will be used if needed. Character values willbe interpreted as CSS lengths (seevalidateCssUnit()), numericvalues as pixels.

cellArgs

Any additional attributes that should be used for each cellof the layout.

See Also

Other layout functions:fillPage(),fixedPage(),flowLayout(),fluidPage(),navbarPage(),sidebarLayout(),verticalLayout()

Examples

## Only run examples in interactive R sessionsif (interactive()) {options(device.ask.default = FALSE)# Server code used for all examplesserver <- function(input, output) {  output$plot1 <- renderPlot(plot(cars))  output$plot2 <- renderPlot(plot(pressure))  output$plot3 <- renderPlot(plot(AirPassengers))}# Equal sizingui <- splitLayout(  plotOutput("plot1"),  plotOutput("plot2"))shinyApp(ui, server)# Custom widthsui <- splitLayout(cellWidths = c("25%", "75%"),  plotOutput("plot1"),  plotOutput("plot2"))shinyApp(ui, server)# All cells at 300 pixels wide, with cell padding# and a border around everythingui <- splitLayout(  style = "border: 1px solid silver;",  cellWidths = 300,  cellArgs = list(style = "padding: 6px"),  plotOutput("plot1"),  plotOutput("plot2"),  plotOutput("plot3"))shinyApp(ui, server)}

Stack trace manipulation functions

Description

Advanced (borderline internal) functions for capturing, printing, andmanipulating stack traces.

Usage

captureStackTraces(expr)withLogErrors(  expr,  full = get_devmode_option("shiny.fullstacktrace", FALSE),  offset = getOption("shiny.stacktraceoffset", TRUE))printError(  cond,  full = get_devmode_option("shiny.fullstacktrace", FALSE),  offset = getOption("shiny.stacktraceoffset", TRUE))printStackTrace(  cond,  full = get_devmode_option("shiny.fullstacktrace", FALSE),  offset = getOption("shiny.stacktraceoffset", TRUE))conditionStackTrace(cond)conditionStackTrace(cond) <- value..stacktraceon..(expr)..stacktraceoff..(expr)

Arguments

expr

The expression to wrap.

full

IfTRUE, then every element ofsys.calls() will beincluded in the stack trace. By default (FALSE), calls that Shinydeems uninteresting will be hidden.

offset

IfTRUE (the default), srcrefs will be reassigned fromthe calls they originated from, to the destinations of those calls. Ifyou're used to stack traces from other languages, this feels moreintuitive, as the definition of the function indicated in the call and thelocation specified by the srcref match up. IfFALSE, srcrefs will beleft alone (traditional R treatment where the srcref is of the callsite).

cond

A condition that may have previously been annotated bycaptureStackTraces (orwithLogErrors).

value

The stack trace value to assign to the condition.

Details

captureStackTraces runs the givenexpr and if anyuncaught errors occur, annotates them with stack trace info for usebyprintError andprintStackTrace. It is not necessary to usecaptureStackTraces around the same expression aswithLogErrors, as the latter includes a call to the former. Notethat ifexpr contains calls (either directly or indirectly) totry, ortryCatch with an error handler, stack traces thereincannot be captured unless anothercaptureStackTraces call isinserted in the interior of thetry ortryCatch. This isbecause these calls catch the error and prevent it from traveling up to thecondition handler installed bycaptureStackTraces.

withLogErrors captures stack traces and logs errors thatoccur inexpr, but does allow errors to propagate beyond this point(i.e. it doesn't catch the error). The same caveats that apply tocaptureStackTraces with regard totry/tryCatch applytowithLogErrors.

printError prints the error and stack trace (if any) usingwarning(immediate.=TRUE).printStackTrace prints the stacktrace only.

conditionStackTrace and⁠conditionStackTrace<-⁠ areaccessor functions for getting/setting stack traces on conditions.

The two functions..stacktraceon.. and..stacktraceoff.. have no runtime behavior during normal execution;they exist only to create artifacts on the stack trace (sys.call()) thatinstruct the stack trace pretty printer what parts of the stack trace areinteresting or not. The initial state is 1 and we walk from the outermostcall inwards. Each ..stacktraceoff.. decrements the state by one, and each..stacktraceon.. increments the state by one. Any stack trace frame whosevalue is less than 1 is hidden, and finally, the ..stacktraceon.. and..stacktraceoff.. calls themselves are hidden too.

Value

printError andprintStackTrace returninvisible(). The other functions pass through the results ofexpr.

Examples

# Keeps tryCatch and withVisible related calls off the# pretty-printed stack tracevisibleFunction1 <- function() {  stop("Kaboom!")}visibleFunction2 <- function() {  visibleFunction1()}hiddenFunction <- function(expr) {  expr}# An example without ..stacktraceon/off.. manipulation.# The outer "try" is just to prevent example() from stopping.try({  # The withLogErrors call ensures that stack traces are captured  # and that errors that bubble up are logged using warning().  withLogErrors({    # tryCatch and withVisible are just here to add some noise to    # the stack trace.    tryCatch(      withVisible({        hiddenFunction(visibleFunction2())      })    )  })})# Now the same example, but with ..stacktraceon/off.. to hide some# of the less-interesting bits (tryCatch and withVisible)...stacktraceoff..({  try({    withLogErrors({      tryCatch(        withVisible(          hiddenFunction(            ..stacktraceon..(visibleFunction2())          )        )      )    })  })})

Stop the currently running Shiny app

Description

Stops the currently running Shiny app, returning control to the caller ofrunApp().

Usage

stopApp(returnValue = invisible())

Arguments

returnValue

The value that should be returned fromrunApp().


Create a submit button

Description

Create a submit button for an app. Apps that include a submitbutton do not automatically update their outputs when inputs change,rather they wait until the user explicitly clicks the submit button.The use ofsubmitButton is generally discouraged in favor ofthe more versatileactionButton() (see details below).

Usage

submitButton(text = "Apply Changes", icon = NULL, width = NULL)

Arguments

text

Button caption

icon

Optionalicon() to appear on the button

width

The width of the button, e.g.'400px', or'100%';seevalidateCssUnit().

Details

Submit buttons are unusual Shiny inputs, and we recommend usingactionButton() instead ofsubmitButton when youwant to delay a reaction.Seethis article for more information (including a demo of how to "translate"code using asubmitButton to code using anactionButton).

In essence, the presence of a submit button stops all inputs fromsending their values automatically to the server. This means, forinstance, that if there aretwo submit buttons in the same app,clicking either one will cause all inputs in the app to send theirvalues to the server. This is probably not what you'd want, which iswhy submit button are unwieldy for all but the simplest apps. Thereare other problems with submit buttons: for example, dynamicallycreated submit buttons (for example, withrenderUI()orinsertUI()) will not work.

Value

A submit button that can be added to a UI definition.

See Also

Other input elements:actionButton(),checkboxGroupInput(),checkboxInput(),dateInput(),dateRangeInput(),fileInput(),numericInput(),passwordInput(),radioButtons(),selectInput(),sliderInput(),textAreaInput(),textInput(),varSelectInput()

Examples

if (interactive()) {shinyApp(  ui = basicPage(    numericInput("num", label = "Make changes", value = 1),    submitButton("Update View", icon("refresh")),    helpText("When you click the button above, you should see",             "the output below update to reflect the value you",             "entered at the top:"),    verbatimTextOutput("value")  ),  server = function(input, output) {    # submit buttons do not have a value of their own,    # they control when the app accesses values of other widgets.    # input$num is the value of the number widget.    output$value <- renderPrint({ input$num })  })}

Create a tab panel

Description

Create a tab panel

Usage

tabPanel(title, ..., value = title, icon = NULL)tabPanelBody(value, ..., icon = NULL)

Arguments

title

Display title for tab

...

UI elements to include within the tab

value

The value that should be sent whentabsetPanel reportsthat this tab is selected. If omitted andtabsetPanel has anid, then the title will be used.

icon

Optional icon to appear on the tab. This attribute is onlyvalid when using atabPanel within anavbarPage().

Value

A tab that can be passed totabsetPanel()

Functions

See Also

tabsetPanel()

Examples

# Show a tabset that includes a plot, summary, and# table view of the generated distributionmainPanel(  tabsetPanel(    tabPanel("Plot", plotOutput("plot")),    tabPanel("Summary", verbatimTextOutput("summary")),    tabPanel("Table", tableOutput("table"))  ))

Table Output

Description

ThetableOuptut()/renderTable() pair creates a reactive table that issuitable for display small matrices and data frames. The columns areformatted withxtable::xtable().

SeerenderDataTable() for data frames that are too big to fit on a singlepage.

Usage

tableOutput(outputId)renderTable(  expr,  striped = FALSE,  hover = FALSE,  bordered = FALSE,  spacing = c("s", "xs", "m", "l"),  width = "auto",  align = NULL,  rownames = FALSE,  colnames = TRUE,  digits = NULL,  na = "NA",  ...,  env = parent.frame(),  quoted = FALSE,  outputArgs = list())

Arguments

outputId

output variable to read the table from

expr

An expression that returns an R object that can be used withxtable::xtable().

striped,hover,bordered

Logicals: ifTRUE, apply thecorresponding Bootstrap table format to the output table.

spacing

The spacing between the rows of the table (xsstands for "extra small",s for "small",m for "medium"andl for "large").

width

Table width. Must be a valid CSS unit (like "100%", "400px","auto") or a number, which will be coerced to a string andhave "px" appended.

align

A string that specifies the column alignment. If equal to'l','c' or'r', then all columns will be,respectively, left-, center- or right-aligned. Otherwise,alignmust have the same number of characters as the resulting table (ifrownames = TRUE, this will be equal toncol()+1), withthei-th character specifying the alignment for thei-th column (besides'l','c' and'r','?' is also permitted -'?' is a placeholderfor that particular column, indicating that it should keep its defaultalignment). IfNULL, then all numeric/integer columns (includingthe row names, if they are numbers) will be right-aligned andeverything else will be left-aligned (align = '?' produces thesame result).

rownames,colnames

Logicals: include rownames? include colnames(column headers)?

digits

An integer specifying the number of decimal places forthe numeric columns (this will not apply to columns with an integerclass). Ifdigits is set to a negative value, then the numericcolumns will be displayed in scientific format with a precision ofabs(digits) digits.

na

The string to use in the table cells whose values are missing(i.e. they either evaluate toNA orNaN).

...

Arguments to be passed through toxtable::xtable()andxtable::print.xtable().

env

The parent environment for the reactive expression. By default,this is the calling environment, the same as when defining an ordinarynon-reactive expression. Ifexpr is a quosure andquoted isTRUE,thenenv is ignored.

quoted

If it isTRUE, then thequote()ed value ofexprwill be used whenexpr is evaluated. Ifexpr is a quosure and youwould like to use its expression as a value forexpr, then you must setquoted toTRUE.

outputArgs

A list of arguments to be passed through to theimplicit call totableOutput() whenrenderTable isused in an interactive R Markdown document.

Examples

## Only run this example in interactive R sessionsif (interactive()) {  # table example  shinyApp(    ui = fluidPage(      fluidRow(        column(12,          tableOutput('table')        )      )    ),    server = function(input, output) {      output$table <- renderTable(iris)    }  )}

Create a tabset panel

Description

Create a tabset that containstabPanel() elements. Tabsets areuseful for dividing output into multiple independently viewable sections.

Usage

tabsetPanel(  ...,  id = NULL,  selected = NULL,  type = c("tabs", "pills", "hidden"),  header = NULL,  footer = NULL)

Arguments

...

tabPanel() elements to include in the tabset

id

If provided, you can use⁠input$⁠id in yourserver logic to determine which of the current tabs is active. The valuewill correspond to thevalue argument that is passed totabPanel().

selected

Thevalue (or, if none was supplied, thetitle)of the tab that should be selected by default. IfNULL, the firsttab will be selected.

type
"tabs"

Standard tab look

"pills"

Selected tabs use the background fill color

"hidden"

Hides the selectable tabs. Usetype = "hidden" inconjunction withtabPanelBody() andupdateTabsetPanel() to control theactive tab via other input controls. (See example below)

header

Tag or list of tags to display as a common header above alltabPanels.

footer

Tag or list of tags to display as a common footer below alltabPanels

Value

A tabset that can be passed tomainPanel()

See Also

tabPanel(),updateTabsetPanel(),insertTab(),showTab()

Examples

# Show a tabset that includes a plot, summary, and# table view of the generated distributionmainPanel(  tabsetPanel(    tabPanel("Plot", plotOutput("plot")),    tabPanel("Summary", verbatimTextOutput("summary")),    tabPanel("Table", tableOutput("table"))  ))ui <- fluidPage(  sidebarLayout(    sidebarPanel(      radioButtons("controller", "Controller", 1:3, 1)    ),    mainPanel(      tabsetPanel(        id = "hidden_tabs",        # Hide the tab values.        # Can only switch tabs by using `updateTabsetPanel()`        type = "hidden",        tabPanelBody("panel1", "Panel 1 content"),        tabPanelBody("panel2", "Panel 2 content"),        tabPanelBody("panel3", "Panel 3 content")      )    )  ))server <- function(input, output, session) {  observeEvent(input$controller, {    updateTabsetPanel(session, "hidden_tabs", selected = paste0("panel", input$controller))  })}if (interactive()) {  shinyApp(ui, server)}

Reactive testing for Shiny server functions and modules

Description

A way to test the reactive interactions in Shiny applications. Reactiveinteractions are defined in the server function of applications and inmodules.

Usage

testServer(app = NULL, expr, args = list(), session = MockShinySession$new())

Arguments

app

A server function (i.e. a function withinput,output,andsession), or a module function (i.e. a function with firstargumentid that callsmoduleServer().

You can also provide an app, a path an app, or anything thatas.shiny.appobj() can handle.

expr

Test code containing expectations. The objects from inside theserver function environment will be made available in the environment ofthe test expression (this is done using a data mask withrlang::eval_tidy()). This includes the parameters of the server function(e.g.input,output, andsession), along with any other valuescreated inside of the server function.

args

Additional arguments to pass to the module function. Ifapp isa module, and noid argument is provided, one will be generated andsupplied automatically.

session

TheMockShinySession object to use as thereactive domain. The same session object is used as the domain bothduring invocation of the server or module under test and during evaluationofexpr.

Examples

# Testing a server function  ----------------------------------------------server <- function(input, output, session) {  x <- reactive(input$a * input$b)}testServer(server, {  session$setInputs(a = 2, b = 3)  stopifnot(x() == 6)})# Testing a module --------------------------------------------------------myModuleServer <- function(id, multiplier = 2, prefix = "I am ") {  moduleServer(id, function(input, output, session) {    myreactive <- reactive({      input$x * multiplier    })    output$txt <- renderText({      paste0(prefix, myreactive())    })  })}testServer(myModuleServer, args = list(multiplier = 2), {  session$setInputs(x = 1)  # You're also free to use third-party  # testing packages like testthat:  #   expect_equal(myreactive(), 2)  stopifnot(myreactive() == 2)  stopifnot(output$txt == "I am 2")  session$setInputs(x = 2)  stopifnot(myreactive() == 4)  stopifnot(output$txt == "I am 4")  # Any additional arguments, below, are passed along to the module.})

Create a textarea input control

Description

Create a textarea input control for entry of unstructured text values.

Usage

textAreaInput(  inputId,  label,  value = "",  width = NULL,  height = NULL,  cols = NULL,  rows = NULL,  placeholder = NULL,  resize = NULL,  ...,  autoresize = FALSE,  updateOn = c("change", "blur"))

Arguments

inputId

Theinput slot that will be used to access the value.

label

Display label for the control, orNULL for no label.

value

Initial value.

width

The width of the input, e.g.'400px', or'100%';seevalidateCssUnit().

height

The height of the input, e.g.'400px', or'100%'; seevalidateCssUnit().

cols

Value of the visible character columns of the input, e.g.80.This argument will only take effect if there is not a CSSwidth ruledefined for this element; such a rule could come from thewidth argumentof this function or from a containing page layout such asfluidPage().

rows

The value of the visible character rows of the input, e.g.6.If theheight argument is specified,height will take precedence in thebrowser's rendering.

placeholder

A character string giving the user a hint as to what canbe entered into the control. Internet Explorer 8 and 9 do not support thisoption.

resize

Which directions the textarea box can be resized. Can be one of"both","none","vertical", and"horizontal". The default,NULL,will use the client browser's default setting for resizing textareas.

...

Ignored, included to require named arguments and for futurefeature expansion.

autoresize

IfTRUE, the textarea will automatically resize to fitthe input text.

updateOn

A character vector specifying when the input should beupdated. Options are"change" (default) and"blur". Use"change" toupdate the input immediately whenever the value changes. Use"blur"todelay the input update until the input loses focus (the user moves awayfrom the input), or when Enter is pressed (or Cmd/Ctrl + Enter fortextAreaInput()).

Value

A textarea input control that can be added to a UI definition.

Server value

A character string of the text input. The default value is""unlessvalue is provided.

See Also

updateTextAreaInput()

Other input elements:actionButton(),checkboxGroupInput(),checkboxInput(),dateInput(),dateRangeInput(),fileInput(),numericInput(),passwordInput(),radioButtons(),selectInput(),sliderInput(),submitButton(),textInput(),varSelectInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  textAreaInput("caption", "Caption", "Data Summary", width = "1000px"),  verbatimTextOutput("value"))server <- function(input, output) {  output$value <- renderText({ input$caption })}shinyApp(ui, server)}

Create a text input control

Description

Create an input control for entry of unstructured text values

Usage

textInput(  inputId,  label,  value = "",  width = NULL,  placeholder = NULL,  ...,  updateOn = c("change", "blur"))

Arguments

inputId

Theinput slot that will be used to access the value.

label

Display label for the control, orNULL for no label.

value

Initial value.

width

The width of the input, e.g.'400px', or'100%';seevalidateCssUnit().

placeholder

A character string giving the user a hint as to what canbe entered into the control. Internet Explorer 8 and 9 do not support thisoption.

...

Ignored, included to require named arguments and for futurefeature expansion.

updateOn

A character vector specifying when the input should beupdated. Options are"change" (default) and"blur". Use"change" toupdate the input immediately whenever the value changes. Use"blur"todelay the input update until the input loses focus (the user moves awayfrom the input), or when Enter is pressed (or Cmd/Ctrl + Enter fortextAreaInput()).

Value

A text input control that can be added to a UI definition.

Server value

A character string of the text input. The default value is""unlessvalue is provided.

See Also

updateTextInput()

Other input elements:actionButton(),checkboxGroupInput(),checkboxInput(),dateInput(),dateRangeInput(),fileInput(),numericInput(),passwordInput(),radioButtons(),selectInput(),sliderInput(),submitButton(),textAreaInput(),varSelectInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  textInput("caption", "Caption", "Data Summary"),  verbatimTextOutput("value"))server <- function(input, output) {  output$value <- renderText({ input$caption })}shinyApp(ui, server)}

Create a text output element

Description

Render a reactive output variable as text within an application page.textOutput() is usually paired withrenderText() and puts regular textin⁠<div>⁠ or⁠<span>⁠;verbatimTextOutput() is usually paired withrenderPrint() and provides fixed-width text in a⁠<pre>⁠.

Usage

textOutput(outputId, container = if (inline) span else div, inline = FALSE)verbatimTextOutput(outputId, placeholder = FALSE)

Arguments

outputId

output variable to read the value from

container

a function to generate an HTML element to contain the text

inline

use an inline (span()) or block container (div())for the output

placeholder

if the output is empty orNULL, should an emptyrectangle be displayed to serve as a placeholder? (does not affectbehavior when the output is nonempty)

Details

In both functions, text is HTML-escaped prior to rendering.

Value

An output element for use in UI.

Examples

## Only run this example in interactive R sessionsif (interactive()) {  shinyApp(    ui = basicPage(      textInput("txt", "Enter the text to display below:"),      textOutput("text"),      verbatimTextOutput("verb")    ),    server = function(input, output) {      output$text <- renderText({ input$txt })      output$verb <- renderText({ input$txt })    }  )}

Create a panel containing an application title.

Description

Create a panel containing an application title.

Usage

titlePanel(title, windowTitle = title)

Arguments

title

An application title to display

windowTitle

The title that should be displayed by the browser window.

Details

Calling this function has the side effect of including atitle tag within the head. You can also specify a page titleexplicitly using thetitle parameter of the top-level page function.

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  titlePanel("Hello Shiny!"))shinyApp(ui, server = function(input, output) { })}

Change the label or icon of an action button on the client

Description

Change the label or icon of an action button on the client

Usage

updateActionButton(  session = getDefaultReactiveDomain(),  inputId,  label = NULL,  icon = NULL,  disabled = NULL)updateActionLink(  session = getDefaultReactiveDomain(),  inputId,  label = NULL,  icon = NULL)

Arguments

session

Thesession object passed to function given toshinyServer. Default isgetDefaultReactiveDomain().

inputId

The id of the input object.

label

The label to set for the input object.

icon

An optionalicon() to appear on the button.

disabled

IfTRUE, the button will not be clickable; ifFALSE, itwill be.

Details

The input updater functions send a message to the client, telling it tochange the settings of an input object. The messages are collected and sentafter all the observers (including outputs) have finished running.

The syntax of these functions is similar to the functions that created theinputs in the first place. For example,numericInput() andupdateNumericInput() take a similar set of arguments.

Any arguments with NULL values will be ignored; they will not result in anychanges to the input object on the client.

ForradioButtons(),checkboxGroupInput() andselectInput(), the set of choices can be cleared by usingchoices=character(0). Similarly, for these inputs, the selected itemcan be cleared by usingselected=character(0).

See Also

actionButton()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  actionButton("update", "Update other buttons and link"),  br(),  actionButton("goButton", "Go"),  br(),  actionButton("goButton2", "Go 2", icon = icon("area-chart")),  br(),  actionButton("goButton3", "Go 3"),  br(),  actionLink("goLink", "Go Link"))server <- function(input, output, session) {  observe({    req(input$update)    # Updates goButton's label and icon    updateActionButton(session, "goButton",      label = "New label",      icon = icon("calendar"))    # Leaves goButton2's label unchanged and    # removes its icon    updateActionButton(session, "goButton2",      icon = character(0))    # Leaves goButton3's icon, if it exists,    # unchanged and changes its label    updateActionButton(session, "goButton3",      label = "New label 3")    # Updates goLink's label and icon    updateActionButton(session, "goLink",      label = "New link label",      icon = icon("link"))  })}shinyApp(ui, server)}

Change the value of a checkbox group input on the client

Description

Change the value of a checkbox group input on the client

Usage

updateCheckboxGroupInput(  session = getDefaultReactiveDomain(),  inputId,  label = NULL,  choices = NULL,  selected = NULL,  inline = FALSE,  choiceNames = NULL,  choiceValues = NULL)

Arguments

session

Thesession object passed to function given toshinyServer. Default isgetDefaultReactiveDomain().

inputId

The id of the input object.

label

The label to set for the input object.

choices

List of values to show checkboxes for. If elements of the listare named then that name rather than the value is displayed to the user. Ifthis argument is provided, thenchoiceNames andchoiceValuesmust not be provided, and vice-versa. The values should be strings; othertypes (such as logicals and numbers) will be coerced to strings.

selected

The values that should be initially selected, if any.

inline

IfTRUE, render the choices inline (i.e. horizontally)

choiceNames,choiceValues

List of names and values, respectively,that are displayed to the user in the app and correspond to the eachchoice (for this reason,choiceNames andchoiceValuesmust have the same length). If either of these arguments isprovided, then the othermust be provided andchoicesmust not be provided. The advantage of using both of these overa named list forchoices is thatchoiceNames allows anytype of UI object to be passed through (tag objects, icons, HTML code,...), instead of just simple text. See Examples.

Details

The input updater functions send a message to the client, telling it tochange the settings of an input object. The messages are collected and sentafter all the observers (including outputs) have finished running.

The syntax of these functions is similar to the functions that created theinputs in the first place. For example,numericInput() andupdateNumericInput() take a similar set of arguments.

Any arguments with NULL values will be ignored; they will not result in anychanges to the input object on the client.

ForradioButtons(),checkboxGroupInput() andselectInput(), the set of choices can be cleared by usingchoices=character(0). Similarly, for these inputs, the selected itemcan be cleared by usingselected=character(0).

See Also

checkboxGroupInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  p("The first checkbox group controls the second"),  checkboxGroupInput("inCheckboxGroup", "Input checkbox",    c("Item A", "Item B", "Item C")),  checkboxGroupInput("inCheckboxGroup2", "Input checkbox 2",    c("Item A", "Item B", "Item C")))server <- function(input, output, session) {  observe({    x <- input$inCheckboxGroup    # Can use character(0) to remove all choices    if (is.null(x))      x <- character(0)    # Can also set the label and select items    updateCheckboxGroupInput(session, "inCheckboxGroup2",      label = paste("Checkboxgroup label", length(x)),      choices = x,      selected = x    )  })}shinyApp(ui, server)}

Change the value of a checkbox input on the client

Description

Change the value of a checkbox input on the client

Usage

updateCheckboxInput(  session = getDefaultReactiveDomain(),  inputId,  label = NULL,  value = NULL)

Arguments

session

Thesession object passed to function given toshinyServer. Default isgetDefaultReactiveDomain().

inputId

The id of the input object.

label

The label to set for the input object.

value

Initial value (TRUE orFALSE).

Details

The input updater functions send a message to the client, telling it tochange the settings of an input object. The messages are collected and sentafter all the observers (including outputs) have finished running.

The syntax of these functions is similar to the functions that created theinputs in the first place. For example,numericInput() andupdateNumericInput() take a similar set of arguments.

Any arguments with NULL values will be ignored; they will not result in anychanges to the input object on the client.

ForradioButtons(),checkboxGroupInput() andselectInput(), the set of choices can be cleared by usingchoices=character(0). Similarly, for these inputs, the selected itemcan be cleared by usingselected=character(0).

See Also

checkboxInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  sliderInput("controller", "Controller", 0, 1, 0, step = 1),  checkboxInput("inCheckbox", "Input checkbox"))server <- function(input, output, session) {  observe({    # TRUE if input$controller is odd, FALSE if even.    x_even <- input$controller %% 2 == 1    updateCheckboxInput(session, "inCheckbox", value = x_even)  })}shinyApp(ui, server)}

Change the value of a date input on the client

Description

Change the value of a date input on the client

Usage

updateDateInput(  session = getDefaultReactiveDomain(),  inputId,  label = NULL,  value = NULL,  min = NULL,  max = NULL)

Arguments

session

Thesession object passed to function given toshinyServer. Default isgetDefaultReactiveDomain().

inputId

The id of the input object.

label

The label to set for the input object.

value

The starting date. Either a Date object, or a string inyyyy-mm-dd format. If NULL (the default), will use the current datein the client's time zone.

min

The minimum allowed date. Either a Date object, or a string inyyyy-mm-dd format.

max

The maximum allowed date. Either a Date object, or a string inyyyy-mm-dd format.

Details

The input updater functions send a message to the client, telling it tochange the settings of an input object. The messages are collected and sentafter all the observers (including outputs) have finished running.

The syntax of these functions is similar to the functions that created theinputs in the first place. For example,numericInput() andupdateNumericInput() take a similar set of arguments.

Any arguments with NULL values will be ignored; they will not result in anychanges to the input object on the client.

ForradioButtons(),checkboxGroupInput() andselectInput(), the set of choices can be cleared by usingchoices=character(0). Similarly, for these inputs, the selected itemcan be cleared by usingselected=character(0).

See Also

dateInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  sliderInput("n", "Day of month", 1, 30, 10),  dateInput("inDate", "Input date"))server <- function(input, output, session) {  observe({    date <- as.Date(paste0("2013-04-", input$n))    updateDateInput(session, "inDate",      label = paste("Date label", input$n),      value = date,      min   = date - 3,      max   = date + 3    )  })}shinyApp(ui, server)}

Change the start and end values of a date range input on the client

Description

Change the start and end values of a date range input on the client

Usage

updateDateRangeInput(  session = getDefaultReactiveDomain(),  inputId,  label = NULL,  start = NULL,  end = NULL,  min = NULL,  max = NULL)

Arguments

session

Thesession object passed to function given toshinyServer. Default isgetDefaultReactiveDomain().

inputId

The id of the input object.

label

The label to set for the input object.

start

The initial start date. Either a Date object, or a string inyyyy-mm-dd format. If NULL (the default), will use the currentdate in the client's time zone.

end

The initial end date. Either a Date object, or a string inyyyy-mm-dd format. If NULL (the default), will use the currentdate in the client's time zone.

min

The minimum allowed date. Either a Date object, or a string inyyyy-mm-dd format.

max

The maximum allowed date. Either a Date object, or a string inyyyy-mm-dd format.

Details

The input updater functions send a message to the client, telling it tochange the settings of an input object. The messages are collected and sentafter all the observers (including outputs) have finished running.

The syntax of these functions is similar to the functions that created theinputs in the first place. For example,numericInput() andupdateNumericInput() take a similar set of arguments.

Any arguments with NULL values will be ignored; they will not result in anychanges to the input object on the client.

ForradioButtons(),checkboxGroupInput() andselectInput(), the set of choices can be cleared by usingchoices=character(0). Similarly, for these inputs, the selected itemcan be cleared by usingselected=character(0).

See Also

dateRangeInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  sliderInput("n", "Day of month", 1, 30, 10),  dateRangeInput("inDateRange", "Input date range"))server <- function(input, output, session) {  observe({    date <- as.Date(paste0("2013-04-", input$n))    updateDateRangeInput(session, "inDateRange",      label = paste("Date range label", input$n),      start = date - 1,      end = date + 1,      min = date - 5,      max = date + 5    )  })}shinyApp(ui, server)}

Change the value of a number input on the client

Description

Change the value of a number input on the client

Usage

updateNumericInput(  session = getDefaultReactiveDomain(),  inputId,  label = NULL,  value = NULL,  min = NULL,  max = NULL,  step = NULL)

Arguments

session

Thesession object passed to function given toshinyServer. Default isgetDefaultReactiveDomain().

inputId

The id of the input object.

label

The label to set for the input object.

value

Initial value.

min

Minimum allowed value

max

Maximum allowed value

step

Interval to use when stepping between min and max

Details

The input updater functions send a message to the client, telling it tochange the settings of an input object. The messages are collected and sentafter all the observers (including outputs) have finished running.

The syntax of these functions is similar to the functions that created theinputs in the first place. For example,numericInput() andupdateNumericInput() take a similar set of arguments.

Any arguments with NULL values will be ignored; they will not result in anychanges to the input object on the client.

ForradioButtons(),checkboxGroupInput() andselectInput(), the set of choices can be cleared by usingchoices=character(0). Similarly, for these inputs, the selected itemcan be cleared by usingselected=character(0).

See Also

numericInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  sliderInput("controller", "Controller", 0, 20, 10),  numericInput("inNumber", "Input number", 0),  numericInput("inNumber2", "Input number 2", 0))server <- function(input, output, session) {  observeEvent(input$controller, {    # We'll use the input$controller variable multiple times, so save it as x    # for convenience.    x <- input$controller    updateNumericInput(session, "inNumber", value = x)    updateNumericInput(session, "inNumber2",      label = paste("Number label ", x),      value = x, min = x-10, max = x+10, step = 5)  })}shinyApp(ui, server)}

Update URL in browser's location bar

Description

This function updates the client browser's query string in the location bar.It typically is called from an observer. Note that this will not work inInternet Explorer 9 and below.

Usage

updateQueryString(  queryString,  mode = c("replace", "push"),  session = getDefaultReactiveDomain())

Arguments

queryString

The new query string to show in the location bar.

mode

When the query string is updated, should the current historyentry be replaced (default), or should a new history entry be pushed ontothe history stack? The former should only be used in a live bookmarkingcontext. The latter is useful if you want to navigate between states usingthe browser's back and forward buttons. See Examples.

session

A Shiny session object.

Details

Formode = "push", only three updates are currently allowed:

  1. the query string (format:?param1=val1&param2=val2)

  2. the hash (format:⁠#hash⁠)

  3. both the query string and the hash(format:?param1=val1&param2=val2#hash)

In other words, ifmode = "push", thequeryString must startwith either⁠?⁠ or with⁠#⁠.

A technical curiosity: under the hood, this function is calling the HTML5history API (which is where the names for themode argument come from).Whenmode = "replace", the function called iswindow.history.replaceState(null, null, queryString).Whenmode = "push", the function called iswindow.history.pushState(null, null, queryString).

See Also

enableBookmarking(),getQueryString()

Examples

## Only run these examples in interactive sessionsif (interactive()) {  ## App 1: Doing "live" bookmarking  ## Update the browser's location bar every time an input changes.  ## This should not be used with enableBookmarking("server"),  ## because that would create a new saved state on disk every time  ## the user changes an input.  enableBookmarking("url")  shinyApp(    ui = function(req) {      fluidPage(        textInput("txt", "Text"),        checkboxInput("chk", "Checkbox")      )    },    server = function(input, output, session) {      observe({        # Trigger this observer every time an input changes        reactiveValuesToList(input)        session$doBookmark()      })      onBookmarked(function(url) {        updateQueryString(url)      })    }  )  ## App 2: Printing the value of the query string  ## (Use the back and forward buttons to see how the browser  ## keeps a record of each state)  shinyApp(    ui = fluidPage(      textInput("txt", "Enter new query string"),      helpText("Format: ?param1=val1&param2=val2"),      actionButton("go", "Update"),      hr(),      verbatimTextOutput("query")    ),    server = function(input, output, session) {      observeEvent(input$go, {        updateQueryString(input$txt, mode = "push")      })      output$query <- renderText({        query <- getQueryString()        queryText <- paste(names(query), query,                       sep = "=", collapse=", ")        paste("Your query string is:\n", queryText)      })    }  )}

Change the value of a radio input on the client

Description

Change the value of a radio input on the client

Usage

updateRadioButtons(  session = getDefaultReactiveDomain(),  inputId,  label = NULL,  choices = NULL,  selected = NULL,  inline = FALSE,  choiceNames = NULL,  choiceValues = NULL)

Arguments

session

Thesession object passed to function given toshinyServer. Default isgetDefaultReactiveDomain().

inputId

The id of the input object.

label

The label to set for the input object.

choices

List of values to select from (if elements of the list arenamed then that name rather than the value is displayed to the user). Ifthis argument is provided, thenchoiceNames andchoiceValues must notbe provided, and vice-versa. The values should be strings; other types(such as logicals and numbers) will be coerced to strings.

selected

The initially selected value. If not specified, then itdefaults to the first item inchoices. To start with no items selected,usecharacter(0).

inline

IfTRUE, render the choices inline (i.e. horizontally)

choiceNames,choiceValues

List of names and values, respectively, thatare displayed to the user in the app and correspond to the each choice (forthis reason,choiceNames andchoiceValues must have the same length).If either of these arguments is provided, then the othermust be providedandchoicesmust not be provided. The advantage of using both of theseover a named list forchoices is thatchoiceNames allows any type of UIobject to be passed through (tag objects, icons, HTML code, ...), insteadof just simple text. See Examples.

Details

The input updater functions send a message to the client, telling it tochange the settings of an input object. The messages are collected and sentafter all the observers (including outputs) have finished running.

The syntax of these functions is similar to the functions that created theinputs in the first place. For example,numericInput() andupdateNumericInput() take a similar set of arguments.

Any arguments with NULL values will be ignored; they will not result in anychanges to the input object on the client.

ForradioButtons(),checkboxGroupInput() andselectInput(), the set of choices can be cleared by usingchoices=character(0). Similarly, for these inputs, the selected itemcan be cleared by usingselected=character(0).

See Also

radioButtons()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  p("The first radio button group controls the second"),  radioButtons("inRadioButtons", "Input radio buttons",    c("Item A", "Item B", "Item C")),  radioButtons("inRadioButtons2", "Input radio buttons 2",    c("Item A", "Item B", "Item C")))server <- function(input, output, session) {  observe({    x <- input$inRadioButtons    # Can also set the label and select items    updateRadioButtons(session, "inRadioButtons2",      label = paste("radioButtons label", x),      choices = x,      selected = x    )  })}shinyApp(ui, server)}

Change the value of a select input on the client

Description

Change the value of a select input on the client

Usage

updateSelectInput(  session = getDefaultReactiveDomain(),  inputId,  label = NULL,  choices = NULL,  selected = NULL)updateSelectizeInput(  session = getDefaultReactiveDomain(),  inputId,  label = NULL,  choices = NULL,  selected = NULL,  options = list(),  server = FALSE)updateVarSelectInput(  session = getDefaultReactiveDomain(),  inputId,  label = NULL,  data = NULL,  selected = NULL)updateVarSelectizeInput(  session = getDefaultReactiveDomain(),  inputId,  label = NULL,  data = NULL,  selected = NULL,  options = list(),  server = FALSE)

Arguments

session

Thesession object passed to function given toshinyServer. Default isgetDefaultReactiveDomain().

inputId

The id of the input object.

label

The label to set for the input object.

choices

List of values to select from. If elements of the list arenamed, then that name — rather than the value — is displayed to theuser. It's also possible to group related inputs by providing a named listwhose elements are (either named or unnamed) lists, vectors, or factors. Inthis case, the outermost names will be used as the group labels (leveragingthe⁠<optgroup>⁠ HTML tag) for the elements in the respective sublist. Seethe example section for a small demo of this feature.

selected

The initially selected value (or multiple values ifmultiple = TRUE). If not specified then defaults to the first value forsingle-select lists and no values for multiple select lists.

options

A list of options. See the documentation ofselectize.js(https://selectize.dev/docs/usage)for possible options (character option values insidebase::I() willbe treated as literal JavaScript code; seerenderDataTable()for details).

server

whether to storechoices on the server side, and loadthe select options dynamically on searching, instead of writing allchoices into the page at once (i.e., only use the client-sideversion ofselectize.js)

data

A data frame. Used to retrieve the column names as choices for aselectInput()

Details

The input updater functions send a message to the client, telling it tochange the settings of an input object. The messages are collected and sentafter all the observers (including outputs) have finished running.

The syntax of these functions is similar to the functions that created theinputs in the first place. For example,numericInput() andupdateNumericInput() take a similar set of arguments.

Any arguments with NULL values will be ignored; they will not result in anychanges to the input object on the client.

ForradioButtons(),checkboxGroupInput() andselectInput(), the set of choices can be cleared by usingchoices=character(0). Similarly, for these inputs, the selected itemcan be cleared by usingselected=character(0).

See Also

selectInput()varSelectInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  p("The checkbox group controls the select input"),  checkboxGroupInput("inCheckboxGroup", "Input checkbox",    c("Item A", "Item B", "Item C")),  selectInput("inSelect", "Select input",    c("Item A", "Item B", "Item C")))server <- function(input, output, session) {  observe({    x <- input$inCheckboxGroup    # Can use character(0) to remove all choices    if (is.null(x))      x <- character(0)    # Can also set the label and select items    updateSelectInput(session, "inSelect",      label = paste("Select input label", length(x)),      choices = x,      selected = tail(x, 1)    )  })}shinyApp(ui, server)}

Update Slider Input Widget

Description

Change the value of a slider input on the client.

Usage

updateSliderInput(  session = getDefaultReactiveDomain(),  inputId,  label = NULL,  value = NULL,  min = NULL,  max = NULL,  step = NULL,  timeFormat = NULL,  timezone = NULL)

Arguments

session

Thesession object passed to function given toshinyServer. Default isgetDefaultReactiveDomain().

inputId

The id of the input object.

label

The label to set for the input object.

value

The initial value of the slider, either a number, a date(class Date), or a date-time (class POSIXt). A length one vector willcreate a regular slider; a length two vector will create a double-endedrange slider. Must lie betweenmin andmax.

min,max

The minimum and maximum values (inclusive) that can beselected.

step

Specifies the interval between each selectable value on theslider. EitherNULL, the default, which uses a heuristic to determine thestep size or a single number. If the values are dates,step is in days;if the values are date-times,step is in seconds.

timeFormat

Only used if the values are Date or POSIXt objects. A timeformat string, to be passed to the Javascript strftime library. Seehttps://github.com/samsonjs/strftime for more details. The allowedformat specifications are very similar, but not identical, to those for R'sbase::strftime() function. For Dates, the default is"%F"(like"2015-07-01"), and for POSIXt, the default is"%F %T"(like"2015-07-01 15:32:10").

timezone

Only used if the values are POSIXt objects. A stringspecifying the time zone offset for the displayed times, in the format"+HHMM" or"-HHMM". IfNULL (the default), times willbe displayed in the browser's time zone. The value"+0000" willresult in UTC time.

Details

The input updater functions send a message to the client, telling it tochange the settings of an input object. The messages are collected and sentafter all the observers (including outputs) have finished running.

The syntax of these functions is similar to the functions that created theinputs in the first place. For example,numericInput() andupdateNumericInput() take a similar set of arguments.

Any arguments with NULL values will be ignored; they will not result in anychanges to the input object on the client.

ForradioButtons(),checkboxGroupInput() andselectInput(), the set of choices can be cleared by usingchoices=character(0). Similarly, for these inputs, the selected itemcan be cleared by usingselected=character(0).

See Also

sliderInput()

Examples

## Only run this example in interactive R sessionsif (interactive()) {  shinyApp(    ui = fluidPage(      sidebarLayout(        sidebarPanel(          p("The first slider controls the second"),          sliderInput("control", "Controller:", min=0, max=20, value=10,                       step=1),          sliderInput("receive", "Receiver:", min=0, max=20, value=10,                       step=1)        ),        mainPanel()      )    ),    server = function(input, output, session) {      observe({        val <- input$control        # Control the value, min, max, and step.        # Step size is 2 when input value is even; 1 when value is odd.        updateSliderInput(session, "receive", value = val,          min = floor(val/2), max = val+4, step = (val+1)%%2 + 1)      })    }  )}

Change the selected tab on the client

Description

Change the selected tab on the client

Usage

updateTabsetPanel(  session = getDefaultReactiveDomain(),  inputId,  selected = NULL)updateNavbarPage(  session = getDefaultReactiveDomain(),  inputId,  selected = NULL)updateNavlistPanel(  session = getDefaultReactiveDomain(),  inputId,  selected = NULL)

Arguments

session

Thesession object passed to function given toshinyServer. Default isgetDefaultReactiveDomain().

inputId

The id of thetabsetPanel,navlistPanel,ornavbarPage object.

selected

Thevalue (or, if none was supplied, thetitle)of the tab that should be selected by default. IfNULL, the firsttab will be selected.

See Also

tabsetPanel(),navlistPanel(),navbarPage()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(sidebarLayout(  sidebarPanel(    sliderInput("controller", "Controller", 1, 3, 1)  ),  mainPanel(    tabsetPanel(id = "inTabset",      tabPanel(title = "Panel 1", value = "panel1", "Panel 1 content"),      tabPanel(title = "Panel 2", value = "panel2", "Panel 2 content"),      tabPanel(title = "Panel 3", value = "panel3", "Panel 3 content")    )  )))server <- function(input, output, session) {  observeEvent(input$controller, {    updateTabsetPanel(session, "inTabset",      selected = paste0("panel", input$controller)    )  })}shinyApp(ui, server)}

Change the value of a textarea input on the client

Description

Change the value of a textarea input on the client

Usage

updateTextAreaInput(  session = getDefaultReactiveDomain(),  inputId,  label = NULL,  value = NULL,  placeholder = NULL)

Arguments

session

Thesession object passed to function given toshinyServer. Default isgetDefaultReactiveDomain().

inputId

The id of the input object.

label

The label to set for the input object.

value

Initial value.

placeholder

A character string giving the user a hint as to what canbe entered into the control. Internet Explorer 8 and 9 do not support thisoption.

Details

The input updater functions send a message to the client, telling it tochange the settings of an input object. The messages are collected and sentafter all the observers (including outputs) have finished running.

The syntax of these functions is similar to the functions that created theinputs in the first place. For example,numericInput() andupdateNumericInput() take a similar set of arguments.

Any arguments with NULL values will be ignored; they will not result in anychanges to the input object on the client.

ForradioButtons(),checkboxGroupInput() andselectInput(), the set of choices can be cleared by usingchoices=character(0). Similarly, for these inputs, the selected itemcan be cleared by usingselected=character(0).

See Also

textAreaInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  sliderInput("controller", "Controller", 0, 20, 10),  textAreaInput("inText", "Input textarea"),  textAreaInput("inText2", "Input textarea 2"))server <- function(input, output, session) {  observe({    # We'll use the input$controller variable multiple times, so save it as x    # for convenience.    x <- input$controller    # This will change the value of input$inText, based on x    updateTextAreaInput(session, "inText", value = paste("New text", x))    # Can also set the label, this time for input$inText2    updateTextAreaInput(session, "inText2",      label = paste("New label", x),      value = paste("New text", x))  })}shinyApp(ui, server)}

Change the value of a text input on the client

Description

Change the value of a text input on the client

Usage

updateTextInput(  session = getDefaultReactiveDomain(),  inputId,  label = NULL,  value = NULL,  placeholder = NULL)

Arguments

session

Thesession object passed to function given toshinyServer. Default isgetDefaultReactiveDomain().

inputId

The id of the input object.

label

The label to set for the input object.

value

Initial value.

placeholder

A character string giving the user a hint as to what canbe entered into the control. Internet Explorer 8 and 9 do not support thisoption.

Details

The input updater functions send a message to the client, telling it tochange the settings of an input object. The messages are collected and sentafter all the observers (including outputs) have finished running.

The syntax of these functions is similar to the functions that created theinputs in the first place. For example,numericInput() andupdateNumericInput() take a similar set of arguments.

Any arguments with NULL values will be ignored; they will not result in anychanges to the input object on the client.

ForradioButtons(),checkboxGroupInput() andselectInput(), the set of choices can be cleared by usingchoices=character(0). Similarly, for these inputs, the selected itemcan be cleared by usingselected=character(0).

See Also

textInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  sliderInput("controller", "Controller", 0, 20, 10),  textInput("inText", "Input text"),  textInput("inText2", "Input text 2"))server <- function(input, output, session) {  observe({    # We'll use the input$controller variable multiple times, so save it as x    # for convenience.    x <- input$controller    # This will change the value of input$inText, based on x    updateTextInput(session, "inText", value = paste("New text", x))    # Can also set the label, this time for input$inText2    updateTextInput(session, "inText2",      label = paste("New label", x),      value = paste("New text", x))  })}shinyApp(ui, server)}

Generate a modal dialog that displays a URL

Description

The modal dialog generated byurlModal will display the URL in atextarea input, and the URL text will be selected so that it can be easilycopied. The result fromurlModal should be passed to theshowModal() function to display it in the browser.

Usage

urlModal(url, title = "Bookmarked application link", subtitle = NULL)

Arguments

url

A URL to display in the dialog box.

title

A title for the dialog box.

subtitle

Text to display underneath URL.


Enable/disable busy indication

Description

Busy indicators provide a visual cue to users when the server is busycalculating outputs or otherwise performing tasks (e.g., producingdownloads). When enabled, a spinner is shown on eachcalculating/recalculating output, and a pulsing banner is shown at the top ofthe page when the app is otherwise busy. Busy indication is enabled bydefault for UI created withbslib, but must be enabled otherwise. Toenable/disable, include the result of this function in anywhere in the app'sUI.

Usage

useBusyIndicators(..., spinners = TRUE, pulse = TRUE, fade = TRUE)

Arguments

...

Currently ignored.

spinners

Whether to show a spinner on each calculating/recalculatingoutput.

pulse

Whether to show a pulsing banner at the top of the page when theapp is busy.

fade

Whether to fade recalculating outputs. A value ofFALSE isequivalent tobusyIndicatorOptions(fade_opacity=1).

Details

When bothspinners andpulse are set toTRUE, the pulse isautomatically disabled when spinner(s) are active. When bothspinners andpulse are set toFALSE, no busy indication is shown (other than thegraying out of recalculating outputs).

See Also

busyIndicatorOptions() for customizing the appearance of the busyindicators.

Examples

library(bslib)ui <- page_fillable(  useBusyIndicators(),  card(    card_header(      "A plot",      input_task_button("simulate", "Simulate"),      class = "d-flex justify-content-between align-items-center"    ),    plotOutput("p"),  ))server <- function(input, output) {  output$p <- renderPlot({    input$simulate    Sys.sleep(4)    plot(x = rnorm(100), y = rnorm(100))  })}shinyApp(ui, server)

Validate input values and other conditions

Description

validate() provides convenient mechanism for validating that an outputhas all the inputs necessary for successful rendering. It takes any numberof (unnamed) arguments, each representing a condition to test. If anyof condition fails (i.e. is not"truthy"), a special type oferror is signaled to stop execution. If this error is not handled byapplication-specific code, it is displayed to the user by Shiny.

If you usevalidate() in areactive() validation failures willautomatically propagate to outputs that use the reactive.

Usage

validate(..., errorClass = character(0))need(expr, message = paste(label, "must be provided"), label)

Arguments

...

A list of tests. Each test should equalNULL for success,FALSE for silent failure, or a string for failure with an errormessage.

errorClass

A CSS class to apply. The actual CSS string will have⁠shiny-output-error-⁠ prepended to this value.

expr

An expression to test. The condition will pass if the expressionmeets the conditions spelled out in Details.

message

A message to convey to the user if the validation condition isnot met. If no message is provided, one will be created usinglabel.To fail with no message, useFALSE for the message.

label

A human-readable name for the field that may be missing. Thisparameter is not needed ifmessage is provided, but must be providedotherwise.

need()

An easy way to provide arguments tovalidate() is to useneed(), whichtakes an expression and a string. If the expression is not"truthy" then the string will be used as the error message.

If "truthiness" is flexible for your use case, you'll need to explicitlygenerate a logical values. For example, if you want allowNA but notNULL, you can!is.null(input$foo).

If you need validation logic that differs significantly fromneed(), youcan create your own validation test functions. A passing test should returnNULL. A failing test should return either a string providing the errorto display to the user, or if the failure should happen silently,FALSE.

Alternatively you can usevalidate() within anif statement, which isparticularly useful for more complex conditions:

if (input$x < 0 && input$choice == "positive") {  validate("If choice is positive then x must be greater than 0")}

Examples

## Only run examples in interactive R sessionsif (interactive()) {options(device.ask.default = FALSE)ui <- fluidPage(  checkboxGroupInput('in1', 'Check some letters', choices = head(LETTERS)),  selectizeInput('in2', 'Select a state', choices = c("", state.name)),  plotOutput('plot'))server <- function(input, output) {  output$plot <- renderPlot({    validate(      need(input$in1, 'Check at least one letter!'),      need(input$in2 != '', 'Please choose a state.')    )    plot(1:10, main = paste(c(input$in1, input$in2), collapse = ', '))  })}shinyApp(ui, server)}

Select variables from a data frame

Description

Create a select list that can be used to choose a single or multiple itemsfrom the column names of a data frame.

Usage

varSelectInput(  inputId,  label,  data,  selected = NULL,  multiple = FALSE,  selectize = TRUE,  width = NULL,  size = NULL)varSelectizeInput(inputId, ..., options = NULL, width = NULL)

Arguments

inputId

Theinput slot that will be used to access the value.

label

Display label for the control, orNULL for no label.

data

A data frame. Used to retrieve the column names as choices for aselectInput()

selected

The initially selected value (or multiple values ifmultiple = TRUE). If not specified then defaults to the first value forsingle-select lists and no values for multiple select lists.

multiple

Is selection of multiple items allowed?

selectize

Whether to useselectize.js or not.

width

The width of the input, e.g.'400px', or'100%';seevalidateCssUnit().

size

Number of items to show in the selection box; a larger numberwill result in a taller box. Not compatible withselectize=TRUE.Normally, whenmultiple=FALSE, a select input will be a drop-down list,but whensize is set, it will be a box instead.

...

Arguments passed tovarSelectInput().

options

A list of options. See the documentation ofselectize.js(https://selectize.dev/docs/usage)for possible options (character option values insidebase::I() willbe treated as literal JavaScript code; seerenderDataTable()for details).

Details

By default,varSelectInput() andselectizeInput() use theJavaScript libraryselectize.js(https://selectize.dev/) to instead of the basicselect input element. To use the standard HTML select input element, useselectInput() withselectize=FALSE.

Value

A variable select list control that can be added to a UI definition.

Server value

The resulting serverinput value will be returned as:

Note

The variable selectize input created fromvarSelectizeInput() allowsdeletion of the selected option even in a single select input, which willreturn an empty string as its value. This is the default behavior ofselectize.js. However, the selectize input created fromselectInput(..., selectize = TRUE) will ignore the empty stringvalue when it is a single choice input and the empty string is not in thechoices argument. This is to keep compatibility withselectInput(..., selectize = FALSE).

See Also

updateSelectInput()

Other input elements:actionButton(),checkboxGroupInput(),checkboxInput(),dateInput(),dateRangeInput(),fileInput(),numericInput(),passwordInput(),radioButtons(),selectInput(),sliderInput(),submitButton(),textAreaInput(),textInput()

Examples

## Only run examples in interactive R sessionsif (interactive()) {library(ggplot2)# single selectionshinyApp(  ui = fluidPage(    varSelectInput("variable", "Variable:", mtcars),    plotOutput("data")  ),  server = function(input, output) {    output$data <- renderPlot({      ggplot(mtcars, aes(!!input$variable)) + geom_histogram()    })  })# multiple selections## Not run: shinyApp( ui = fluidPage(   varSelectInput("variables", "Variable:", mtcars, multiple = TRUE),   tableOutput("data") ), server = function(input, output) {   output$data <- renderTable({      if (length(input$variables) == 0) return(mtcars)      mtcars %>% dplyr::select(!!!input$variables)   }, rownames = TRUE) })## End(Not run)}

Lay out UI elements vertically

Description

Create a container that includes one or more rows of content (each elementpassed to the container will appear on it's own line in the UI)

Usage

verticalLayout(..., fluid = TRUE)

Arguments

...

Elements to include within the container

fluid

TRUE to use fluid layout;FALSE to use fixedlayout.

See Also

Other layout functions:fillPage(),fixedPage(),flowLayout(),fluidPage(),navbarPage(),sidebarLayout(),splitLayout()

Examples

## Only run examples in interactive R sessionsif (interactive()) {ui <- fluidPage(  verticalLayout(    a(href="http://example.com/link1", "Link One"),    a(href="http://example.com/link2", "Link Two"),    a(href="http://example.com/link3", "Link Three")  ))shinyApp(ui, server = function(input, output) { })}

Viewer options

Description

Use these functions to control where the gadget is displayed in RStudio (orother R environments that emulate RStudio's viewer pane/dialog APIs). Ifviewer APIs are not available in the current R environment, then the gadgetwill be displayed in the system's default web browser (seeutils::browseURL()).

Usage

paneViewer(minHeight = NULL)dialogViewer(dialogName, width = 600, height = 600)browserViewer(browser = getOption("browser"))

Arguments

minHeight

The minimum height (in pixels) desired to show the gadget inthe viewer pane. If a positive number, resize the pane if necessary to showat least that many pixels. IfNULL, use the existing viewer panesize. If"maximize", use the maximum available vertical space.

dialogName

The window title to display for the dialog.

width,height

The desired dialog width/height, in pixels.

browser

Seeutils::browseURL().

Value

A function that takes a singleurl parameter, suitable forpassing as theviewer argument ofrunGadget().


Create a well panel

Description

Creates a panel with a slightly inset border and grey background. Equivalentto Bootstrap'swell CSS class.

Usage

wellPanel(...)

Arguments

...

UI elements to include inside the panel.

Value

The newly created panel.


Load the MathJax library and typeset math expressions

Description

This function adds MathJax to the page and typeset the math expressions (iffound) in the content.... It only needs to be called once in an appunless the content is renderedafter the page is loaded, e.g. viarenderUI(), in which case we have to call it explicitly everytime we write math expressions to the output.

Usage

withMathJax(...)

Arguments

...

any HTML elements to apply MathJax to

Examples

withMathJax(helpText("Some math here $$\\alpha+\\beta$$"))# now we can just write "static" content without withMathJax()div("more math here $$\\sqrt{2}$$")

Temporarily set OpenTelemetry (OTel) collection level

Description

Control Shiny's OTel collection level for particular reactive expression(s).

withOtelCollect() sets the OpenTelemetry collection level forthe duration of evaluatingexpr.localOtelCollect() sets the collectionlevel for the remainder of the current function scope.

Usage

withOtelCollect(collect, expr)localOtelCollect(collect, envir = parent.frame())

Arguments

collect

Character string specifying the OpenTelemetry collection level.Must be one of the following:

* `"none"` - No telemetry data collected* `"reactivity"` - Collect reactive execution spans (includes session and  reactive update events)* `"all"` - All available telemetry (currently equivalent to `"reactivity"`)
expr

Expression to evaluate with the specified collection level(forwithOtelCollect()).

envir

Environment where the collection level should be set(forlocalOtelCollect()). Defaults to the parent frame.

Details

Note that"session" and"reactive_update" levels are not permitted asthese are runtime-specific levels that should only be set permanently viaoptions(shiny.otel.collect = ...) or theSHINY_OTEL_COLLECT environmentvariable, not temporarily during reactive expression creation.

Value

Best practice

Best practice is to set the collection level for code thatcreates reactiveexpressions, not code thatruns them. For instance:

# Disable telemetry for a reactive expressionwithOtelCollect("none", {  my_reactive <- reactive({ ... })})# Disable telemetry for a render functionwithOtelCollect("none", {  output$my_plot <- renderPlot({ ... })})#' # Disable telemetry for an observerwithOtelCollect("none", {  observe({ ... }))})# Disable telemetry for an entire modulewithOtelCollect("none", {  my_result <- my_module("my_id")})# Use `my_result` as normal here

NOTE: It's not recommended to pipe existing reactive objects intowithOtelCollect() since they won't inherit their intended OTel settings,leading to confusion.

See Also

See theshiny.otel.collect option withinshinyOptions. Settingthis value will globally control OpenTelemetry collection levels.

Examples

## Not run: # Temporarily disable telemetry collectionwithOtelCollect("none", {  # Code here won't generate telemetry  reactive({ input$x + 1 })})# Collect reactivity telemetry but not other eventswithOtelCollect("reactivity", {  # Reactive execution will be traced  observe({ print(input$x) })})# Use local variant in a functionmy_function <- function() {  localOtelCollect("none")  # Rest of function executes without telemetry  reactive({ input$y * 2 })}## End(Not run)

Reporting progress (functional API)

Description

Reports progress to the user during long-running operations.

Usage

withProgress(  expr,  min = 0,  max = 1,  value = min + (max - min) * 0.1,  message = NULL,  detail = NULL,  style = getShinyOption("progress.style", default = "notification"),  session = getDefaultReactiveDomain(),  env = parent.frame(),  quoted = FALSE)setProgress(  value = NULL,  message = NULL,  detail = NULL,  session = getDefaultReactiveDomain())incProgress(  amount = 0.1,  message = NULL,  detail = NULL,  session = getDefaultReactiveDomain())

Arguments

expr

The work to be done. This expression should contain calls tosetProgress() orincProgress().

min

The value that represents the starting point of the progress bar.Must be less thammax. Default is 0.

max

The value that represents the end of the progress bar. Must begreater thanmin. Default is 1.

value

Single-element numeric vector; the value at which to set theprogress bar, relative tomin andmax.

message

A single-element character vector; the message to be displayedto the user, orNULL to hide the current message (if any).

detail

A single-element character vector; the detail message to bedisplayed to the user, orNULL to hide the current detail message(if any). The detail message will be shown with a de-emphasized appearancerelative tomessage.

style

Progress display style. If"notification" (the default),the progress indicator will show using Shiny's notification API. If"old", use the same HTML and CSS used in Shiny 0.13.2 and below(this is for backward-compatibility).

session

The Shiny session object, as provided byshinyServer tothe server function. The default is to automatically find the session byusing the current reactive domain.

env

The environment in whichexpr should be evaluated.

quoted

Whetherexpr is a quoted expression (this is notcommon).

amount

ForincProgress, the amount to increment the status bar.Default is 0.1.

Details

This package exposes two distinct programming APIs for working with progress.UsingwithProgress withincProgress orsetProgressprovide a simple function-based interface, while theProgress()reference class provides an object-oriented API.

UsewithProgress to wrap the scope of your work; doing so will cause anew progress panel to be created, and it will be displayed the first timeincProgress orsetProgress are called. WhenwithProgressexits, the corresponding progress panel will be removed.

TheincProgress function increments the status bar by a specifiedamount, whereas thesetProgress function sets it to a specific value,and can also set the text displayed.

Generally,withProgress/incProgress/setProgress shouldbe sufficient; the exception is if the work to be done is asynchronous (thisis not common) or otherwise cannot be encapsulated by a single scope. In thatcase, you can use theProgress reference class.

As of version 0.14, the progress indicators use Shiny's new notification API.If you want to use the old styling (for example, you may have used customizedCSS), you can usestyle="old" each time you callwithProgress(). If you don't want to set the style each timewithProgress is called, you can instead callshinyOptions(progress.style="old") just once, inside the serverfunction.

Value

The result ofexpr.

See Also

Progress()

Examples

## Only run examples in interactive R sessionsif (interactive()) {options(device.ask.default = FALSE)ui <- fluidPage(  plotOutput("plot"))server <- function(input, output) {  output$plot <- renderPlot({    withProgress(message = 'Calculation in progress',                 detail = 'This may take a while...', value = 0, {      for (i in 1:15) {        incProgress(1/15)        Sys.sleep(0.25)      }    })    plot(cars)  })}shinyApp(ui, server)}

[8]ページ先頭

©2009-2025 Movatter.jp