Input functions in RShiny - Answer Key

Author

Will Gammerdinger

Published

November 5, 2025

Exercise 1

Let’s focus on creating this app in several parts:

  1. Create two selectInput() menus to choose the x- and y-axis to plot along with the resulting output plot.
library(shiny)
library(DT)
library(tidyverse)

# User Interface
ui <- fluidPage(
  # Dropdown menu to select which column will be used for the x-axis
  selectInput(inputId = "x_axis_input",
              label = "Select x-axis",
              choices = colnames(mtcars),
              selected = "mpg"), 
   # Dropdown menu to select which column will be used for the y-axis
  selectInput(inputId = "y_axis_input",
              label = "Select y-axis",
              choices = colnames(mtcars),
              selected = "disp"),
  # The output plot
  plotOutput(outputId = "plot")
)

# Server
server <- function(input, output) {
  # Render the scatter plot
  output$plot <- renderPlot({
    # Scatter plot creation
    ggplot(mtcars) +
      geom_point(aes_string(x = input$x_axis_input, y = input$y_axis_input))
  })
}

# Run the app
shinyApp(ui = ui, server = server)
  1. Add to our app the ability to brush over the plot and select points to place in a table beneath the plot.
library(shiny)
library(DT)
library(tidyverse)

# User Interface
ui <- fluidPage(
  # Dropdown menu to select which column will be used for the x-axis
  selectInput(inputId = "x_axis_input",
              label = "Select x-axis",
              choices = colnames(mtcars),
              selected = "mpg"), 
   # Dropdown menu to select which column will be used for the y-axis
  selectInput(inputId = "y_axis_input",
              label = "Select y-axis",
              choices = colnames(mtcars),
              selected = "disp"),
  # The output plot
  plotOutput(outputId = "plot",
             brush = "plot_brush"),
  # The output table
  DTOutput("table")
)

# Server
server <- function(input, output) {
  # Render the scatter plot
  output$plot <- renderPlot({
    # Scatter plot creation
    ggplot(mtcars) +
      geom_point(aes_string(x = input$x_axis_input, y = input$y_axis_input))
  })
  # Render a table from points within the rectangle created by clicking and dragging over the plot
  output$table <- renderDT({
    brushedPoints(mtcars, input$plot_brush)
  })
}

# Run the app
shinyApp(ui = ui, server = server)

Reuse

CC-BY-4.0