Tidyeval with ggplot() & pmap()

I'm having an issue while using pmap() with tidyeval and ggplot(). Not sure what I'm missing.

The code below works as desired:

library(tidyverse)

scatter_plot <- function(x,y,alpha, facet){
  x_val <- enquo(x)
  y_val <- enquo(y)
  facet_var <- enquo(facet)
  
  ggplot(iris, aes(!!x_val, !!y_val, alpha=alpha)) + geom_point() +
    facet_wrap(vars(!!facet_var),ncol = 3)
}

scatter_plot(Petal.Length, Sepal.Length, 0.5, Species)

image1

However using pmap() to pass a list of argument vectors doesn't give the desired plots:

x <- c("Petal.Length","Petal.Width")
y <- c("Sepal.Length","Sepal.Width")
alpha <- c(0.4,0.8)
facet <- rep("Species",2)

pmap(list(x,y,alpha,facet), scatter_plot)
#> [[1]]

image2

#> 
#> [[2]]

image3

Created on 2018-11-06 by the reprex package (v0.2.1)

Hi, there is a big difference between how you use your function first time and second time. First time you are giving it unquoted symbols that you indeed need to use enquo to capture. Second time you are giving it quoted input (strings), so enquo no longer works since when unquoted with !! it returns a string (e.g., "Petal.Width" or whatever, not symbol that you actually need).
So the solution is to use ensym instead and then everything works. I've also changed pmap to pwalk since it clarifies that your output is a side-effect (i.e., printing plot to console):

library(tidyverse)

scatter_plot <- function(x,y,alpha, facet){
  x_val <- ensym(x)
  y_val <- ensym(y)
  facet_var <- ensym(facet)
  
  p <- ggplot(iris, aes(!!x_val, !!y_val, alpha=alpha)) + geom_point() +
    facet_wrap(vars(!!facet_var),ncol = 3)
  print(p)
}

#scatter_plot(Petal.Length, Sepal.Length, 0.5, Species)

x <- c("Petal.Length","Petal.Width")
y <- c("Sepal.Length","Sepal.Width")
alpha <- c(0.4,0.8)
facet <- rep("Species",2)

pwalk(list(x,y,alpha,facet), scatter_plot)

Created on 2018-11-06 by the reprex package (v0.2.1)

5 Likes

Thank you! I had tried getting rid of the quotes with noquote() before enquo() but that didn't work.

If your question's been answered (even if by you), would you mind choosing a solution? (See FAQ below for how).

Having questions checked as resolved makes it a bit easier to navigate the site visually and see which threads still need help.

Thanks

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.