Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

r - standard eval with ggplot2 without `aes_string()`

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...