Tidy evaluation in R, or tidy eval for short, is a pretty complex topic. But for some specific uses, it’s not all that complex. One important task that tidy eval helps handle is both useful and easy: incorporating functions from packages such as dplyr and ggplot2 inside your own custom functions.

Let me go through an example. Using the ubiquitous mtcars sample data set, here’s how I might do a scatterplot of miles per gallon by weight, using dplyr to filter for higher-mpg cars only (I’ve also added a few style tweaks):

library(ggplot2)
library(ggthemes)
library(dplyr)
library(rlang)
graph_title <- "MPG by Weight (thousands lbs) for higher MPG cars"
filter(mtcars, mpg >= 20) %>%
ggplot(aes(x=wt, y=mpg)) +
geom_point(color = "darkblue") +
theme_hc() + xlab("") + ylab("") +
ggtitle(graph_title) +
theme(plot.title = element_text(size = 14, hjust = 0.5)) +
geom_smooth(method = 'lm', formula = y~x, se = FALSE, linetype = "dotted", color = "darkgrey")

Next, I’d like to create a function with this code, so I can easily reuse these customizations to plot other data, not just mtcars. That’s where problems arise that tidy eval can solve.

Here’s a first try at creating that function. It simply wraps my graph code in a new function:

fun1 <- function(mydf, mytitle, myxcol, myycol, minyval = 20){
dplyr::filter(mydf, myycol >= minyval) %>%
ggplot(aes(x=myxcol, y=myycol)) +
geom_point(color = "darkblue") +
theme_hc() + xlab("") + ylab("") +
ggtitle(mytitle) +
theme(plot.title = element_text(size = 14, hjust = 0.5)) +
geom_smooth(method = 'lm', formula = y~x, se = FALSE, linetype = "dotted", color = "darkgrey")
}

To use this function, it’s pretty straightforward to add the graph title, the data frame, and a default minimum value as arguments. But you’ll run into problems with the data frame column names.

If I use wt and mpg unquoted as arguments in my function, like ggplot does, I get an error. You’ll see this if you run fun1(mydf = mtcars, mytitle =" MPG by Weight (thousands of pounds", wt, mpg)

, aren’t cringing in horror at this explanation if they’re reading. But it works for me for this basic use case. I hope it works for you, too.

There’s a lot more to know about tidy eval, and more operators in the rlang package. You can read more from RStudio at .