How does enquote/quote/!! works in ggplot

Viewed 173

I want to build a function where I can pass a variable name as a string and it would return me a ggplot object.

This one works:

myplot <- function(x, y) {
  ggplot(data, aes_string(x="x", y="y")) + geom_bar()
}

but in ggplot documentation:

  1. It is write (I cite): "I recommend using aes_()" and
  2. "All these functions are soft-deprecated. Please use tidy evaluation idioms instead"

But at that moment I figured out that I do not understand how to use aes_ (to build an example as above, and I don't understand how to enquotation, quotation, quasiquotation means. There is a lot of literature on this in the net, but if someone could show me on this specific example how it works it probably gives me a hint to proceed from here.

1 Answers

The aes_string is deprecated. If we are passing strings, then convert to symbol and evaluate with !!

library(ggplot2)
library(dplyr)
myplot <- function(x, y) {
  ggplot(data, aes(x= !! rlang::sym(x), y= !! rlang::sym(y))) + geom_bar()
   }

If we pass unquoted, then use curly-curly operator{{}}

myplot <- function(x, y) {
     ggplot(data, aes(x= {{x}}, y= {{y}})) + geom_bar()
   }

The curly-curly operator does the enquo with !!

myplot <- function(x, y) {
     ggplot(data, aes(x= !! enquo(x), y= !! enquo(y))) + geom_bar()
   }

If we want to pass either quoted or unquoted, use ensym

myplot <- function(x, y) {
     ggplot(data, aes(x= !! ensym(x), y= !! ensym(y))) + geom_bar()
   }

NOTE: It is also better to have the data as parameter to the function

Related