gpt4 book ai didi

r - 带有 ggplot2 的标准 eval 没有 `aes_string()`

转载 作者:行者123 更新时间:2023-12-04 17:14:37 30 4
gpt4 key购买 nike

我想将带引号的字符串传递给调用 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() .

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



但是 aes() examples使用 NSE(即, g1(mpg) 而不是 g1("mpg") )。同样,这些 SO 解决方案使用 NSE 值或 aes_()/ aes_string() .
  • Use dplyr SE with ggplot2
  • How to use dplyr's enquo and quo_name in a function with tidyr and ggplot2
  • Why does this aes tidyeval example from ggplot documentation throw an error?

  • 我希望函数接受一个 SE/带引号的字符串,以容纳一个字符向量,例如:
    variables <- c("mpg", "cyl", "disp")
    variables %>%
    lapply(g1)

    最佳答案

    您可以使用 !! 执行此操作调用 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)

    关于r - 带有 ggplot2 的标准 eval 没有 `aes_string()`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55132771/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com