Session 1.2–R Shiny Basics
Two parts of a Shiny app:
They come together in a single script: app.R
ui
)fluidPage()
creates a Bootstrap page
Under the hood, every UI function is translated to HTML.
This HTML can have styles attached to it, either by the style
attribute, or by a CSS class.
To let users interact with your app, you can add input controls. A basic input control has:
inputId
label
value
For example:
Shiny has several functions that turn R objects into reactive outputs for your ui
: the Output family of functions.
Each function creates a specific type of output, for example:
UI Function | Output type |
---|---|
textOutput() | text |
tableOutput() | table |
plotOutput() | plot |
uiOutput() | raw HTML |
Every output element needs a single argument: outputId
. This is a simple string that needs to be unique.
This textOutput
tells Shiny what to display. It’s a placeholder for what is goign to be produced by the server logic.
output$text
Each entry in the output list should contain a Render function. You must use Render functions that match the Output functions:
UI Function | Output type | Render function |
---|---|---|
textOutput() | text | renderText() |
tableOutput() | table | renderTable() |
plotOutput() | plot | renderPlot() |
uiOutput() | raw HTML | renderUI() |
input
that will contain the value of all the input objects defined in the UI.input$number
.Combining the input and output objects, we get a simple app that displays the square of a number. 👏
10:00
An output is eager: it will update as soon as the input changes.
This eagerness is handy: you don’t need to worry about updating the output when the input changes.
But what if you want to trigger the calculation only when you want?
You could use an actionButton
as an event:
library(shiny)
ui <- fluidPage(
numericInput(inputId = "number",
label = "Enter a number",
value = 0),
actionButton(inputId = "button",
label = "Click me"),
textOutput(outputId = "text")
)
server <- function(input, output, session) {
output$text <- renderText({
input$number^2
}) |> bindEvent(input$button)
}
shinyApp(ui, server)
actionButton
to your app