【问题标题】:standard eval with ggplot2 without `aes_string()`带有 ggplot2 的标准 eval 没有 `aes_string()`
【发布时间】:2019-03-13 00:49:29
【问题描述】:

我想将带引号的字符串传递给调用 ggplot2 的函数。

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

这很好用,但 v3.1.0 documentation 提倡准引用和 NSE aes()

所有这些功能都已软弃用。请改用整洁的评估习语(请参阅 aes() 文档中的 quasiquotation 部分)。

aes() examples 使用 NSE(ieg1(mpg) 而不是 g1("mpg"))。同样,这些 SO 解决方案使用 NSE 值或 aes_()/aes_string()

我希望该函数接受 SE/带引号的字符串,以容纳字符向量,例如:

variables <- c("mpg", "cyl", "disp")
variables %>% 
  lapply(g1)

【问题讨论】:

标签: r ggplot2 standard-evaluation


【解决方案1】:

您可以在调用sym 后对变量使用!! 运算符来执行此操作。这将取消引用并评估周围环境中的variable

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)

【讨论】:

    【解决方案2】:

    一种解决方法是用一个通用名称替换您函数中感兴趣的变量名称:

    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)
    

    【讨论】:

    • 这很好,特别是如果有多个映射变量需要是动态的,因此每个变量都不需要运算符/函数(即!!sym())。跨度>
    • 顺便说一句,我可能会将 gsub() 更改为 sub() 并收紧模式,使其必须完全匹配(不仅仅是在变量名中间的某个位置)。也许像paste0("^", variable, "$") 这样的东西。或者用dplyr::rename()替换名字,我猜!!
    猜你喜欢
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    相关资源
    最近更新 更多