1

I am trying to write a wrapper function around ggplot, but I keep coming up with an error when unquoting a function parameter:

Error in !enquo(x) : invalid argument type

I have re-read the dplyr programming guide, and thought I understood it and have used tidyeval previously in implementing functions using dplyr verbs eg group_by and mutate. This brought me to the ggplot documentation for aes where I found this example:

scatter_by <- function(data, x, y) {
  ggplot(data) + geom_point(aes(!!enquo(x), !!enquo(y)))
}
scatter_by(mtcars, disp, drat)

When I run this in RStudio 1.1.383, I get the error:

Error in !enquo(x) : invalid argument type

I am using ggplot2 version 2.2.1 and dplyr 0.7.4

I have tried using rlang::UQ(enquo(x)) instead of !! but I still get an error.

r_nurse
  • 11
  • 2
  • Your code seems fine and it worked as well on my pc, I am using ggplot version : `ggplot2_2.2.1.9000` – PKumar Jun 20 '18 at 09:32
  • Using tidyeval in ggplot2 is a feature that will be part of the [next release](https://github.com/tidyverse/ggplot2/blob/master/NEWS.md#ggplot2-2219000), which I believe is imminent. You can install the development version [from github](https://github.com/tidyverse/ggplot2#ggplot2-) if you'd like to use that feature now. – aosmith Jun 20 '18 at 14:20

1 Answers1

1

You can use aes_string and quo_name.

scatter_by <- function(data, x, y) {

  ggplot(data) + 
    geom_point(aes_string(x= quo_name(enquo(x)), y=quo_name(enquo(y))))

}
scatter_by(mtcars, disp, drat)

Here is quite substantial disscusion about this problem: How to use dplyr's enquo and quo_name in a function with tidyr and ggplot2

MikolajM
  • 354
  • 1
  • 8
  • Thank you for your reply and link. aes should support tidyeval without needing to use aes_string, should it not? This has made my wrapper function work, I would just like a tidier version – r_nurse Jun 20 '18 at 09:30
  • According to the documentation it should but apparently it does not work. I checked it on dplyr 0.7.4 and 0.7.5 without success. Maybe it is worth to report it on ggplot2's github? – MikolajM Jun 20 '18 at 10:34