standard eval with ggplot2 without `aes_string()`

前端 未结 2 1130
不知归路
不知归路 2021-01-12 23:08

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

library(magrittr); library(ggplot2)
g1 <- function( variable ) {
  ggplot(mtcars, aes_         


        
相关标签:
2条回答
  • 2021-01-12 23:22

    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)
    
    0 讨论(0)
  • 2021-01-12 23:30

    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)
    
    0 讨论(0)
提交回复
热议问题