Chapter 11 Tidy evaluation

If you are using the tidyverse from shiny, you will almost certainly encounter the challenge of programming with tidy evaluation. Tidy evaluation is the technique that allows you to refer to variables within a data frame, without having to think about it, or do anything special. That’s what makes code like this work:

The problem that you will quickly encouter with Shiny is that you want to write code like:

But this doesn’t work because dplyr and ggplot2 will attempt to look for a variable called input in

There are two primary cases:

  • You want the user to select variables in the app.
  • You want to reduce duplication in your app code.

11.1 User selections

Key challenge is to turn the string giving the name of the variable (e.g. "cyl") into a variable. The way to do that with tidy evaluation is with the special .data pronoun.

(I use the special ggforce::position_auto() to automatically spread the points out when one axis is discretes)

http://ggplot2.tidyverse.org/dev/articles/ggplot2-in-packages.html

This will work with any input that returns a string.

Same idea works for dplyr:

What if you wanted to conditionally sort in either asceding or descending order?

As you provide more control, you’ll find the code gets more and more complicated, and it becomes harder and harder to create a user interface that is both comprehensive and user friendly. This is why I’ve always focussed on code tools for data analysis: creating good UIs is really really hard!

11.1.1 parse()

You may have considered using parse() + eval(). This is a bad idea because it means that the user of your app can run arbitrary R code. This isn’t super important if its a Shiny app that only use you, but it’s a good habit to get into — otherwise it’s very easy to accidentally create a security hole in an app that you share more widely.