Get startedGet started for free

Constructing output objects

There are three rules to build an output in Shiny:

  1. Build the object with the appropriate render*() function.

  2. Save the result of the render function into the output list, which is a parameter of the server function. Specifically, save it into output$<outputId> in order to replace the output placeholder in the UI that has ID outputId.

  3. If the output relies on any user-modified input values, you can access any of the inputs using the input parameter of the server function. Specifically, input$<inputId> will always return the current value of the input field that has ID inputId.

This exercise is part of the course

Case Studies: Building Web Applications with Shiny in R

View Course

Exercise instructions

You are given a Shiny app with a fully functional UI portion. Your task is to construct all the outputs. Specifically:

  • Create a plot of the cars dataset in the plot output placeholder with ID "cars_plot" (line 23).
  • In the "greeting" text output, render a text greeting in the form of "Hello NAME", where NAME is the value of the name input (line 28).
  • In the "iris_table" output, show a table of the first n rows of the iris dataset, where n is the value of the numeric input (line 33).

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Load the shiny package
library(shiny)

# Define UI for the application
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      textInput("name", "What is your name?", "Dean"),
      numericInput("num", "Number of flowers to show data for",
                   10, 1, nrow(iris))
    ),
    mainPanel(
      textOutput("greeting"),
      plotOutput("cars_plot"),
      tableOutput("iris_table")
    )
  )
)

# Define the server logic
server <- function(input, output) {
  # Create a plot of the "cars" dataset 
  output$cars_plot <- render___({
    plot(cars)
  })
  
  # Render a text greeting as "Hello "
  output$greeting <- ___({
    paste("Hello", ___)
  })
  
  # Show a table of the first n rows of the "iris" data
  ___ <- ___({
    data <- iris[1:input$num, ]
    data
  })
}

# Run the application
shinyApp(ui = ui, server = server)
Edit and Run Code