Chapter 12. Tidy Evaluation

If you are using Shiny with the tidyverse, you will almost certainly encounter the challenge of programming with tidy evaluation. Tidy evaluation is used throughout the tidyverse to make interactive data exploration more fluid, but it comes with a cost: it’s hard to refer to variables indirectly and hence harder to program with.

In this chapter, you’ll learn how to wrap ggplot2 and dplyr functions in a Shiny app. (If you don’t use the tidyverse, you can skip this chapter smile.) The techniques for wrapping ggplot2 and dplyr functions in other functions or a package are a little different and are covered in other resources like Using ggplot2 in Packages or Programming with dplyr. Let’s get started:

library(shiny)
library(dplyr, warn.conflicts = FALSE)
library(ggplot2)

Motivation

Imagine I want to create an app that allows you to filter a numeric variable to select rows that are greater than a threshold. You might write something like this:

num_vars <- c("carat", "depth", "table", "price", "x", "y", "z")
ui <- fluidPage(
  selectInput("var", "Variable", choices = num_vars),
  numericInput("min", "Minimum", value = 1),
  tableOutput("output")
)
server <- function(input, output, session) {
  data <- reactive(diamonds %>% filter(input$var > input$min))
  output$output <- renderTable(head(data()))
}
Figure 12-1. An app that tries to select rows that are greater ...

Get Mastering Shiny now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.