13

I'd like to pass a quoted string to a function that calls ggplot2.

library(magrittr); library(ggplot2)
g1 <- function( variable ) {
  ggplot(mtcars, aes_string("wt", variable, size="carb")) +
    geom_point()
}
g1("mpg")

This works well, but the v3.1.0 documentation advocates quasiquotation and the NSE aes().

All these functions are soft-deprecated. Please use tidy evaluation idioms instead (see the quasiquotation section in aes() documentation).

But the aes() examples use NSE (ie, g1(mpg) instead of g1("mpg")). Likewise, these SO solutions use either NSE values or aes_()/aes_string().

I'd like the function to accept a SE/quoted string, to accommodate a character vector, like:

variables <- c("mpg", "cyl", "disp")
variables %>% 
  lapply(g1)
wibeasley
  • 5,000
  • 3
  • 34
  • 62

2 Answers2

17

You can do this using the !! operator on the variable after call to sym. This will unquote and evaluate variable in the surrounding environement.

library(rlang)
g1 <- function( variable ) {
  ggplot(mtcars, aes(x = wt, y = !! sym(variable) , size = "carb")) +
    geom_point()
}
g1("mpg")

variables <- c("mpg", "cyl", "disp")
variables %>% 
  lapply(g1)
Croote
  • 1,382
  • 1
  • 7
  • 15
4

A work-around is to substitute a common name for the variable name of interest in your function:

g1 <- function( variable ) {
  colnames(mtcars) <- gsub(variable, "variable", colnames(mtcars))
  ggplot(mtcars, aes(x=wt, y=variable, size=carb)) +
    geom_point() + ylab(variable)
}

variables <- c("mpg", "cyl", "disp")
variables %>% 
  lapply(g1)
Djork
  • 3,319
  • 1
  • 16
  • 27
  • This is nice, especially if there are multiple mapped variables that need to be dynamic, so each variable doesn't need to operators/functions (ie, `!!` and `sym()`). – wibeasley Mar 13 '19 at 14:49
  • 2
    Btw, I might change `gsub()` to `sub()` and tighten up the pattern so it had to match exactly (not just somewhere in the middle of the variable name). Maybe something like `paste0("^", variable, "$")`. Or replace the names with `dplyr::rename()` and I guess `!!`. – wibeasley Mar 13 '19 at 14:50