将不带引号的变量传递给卷曲的{{}} ggplot函数

时间:2019-12-02 15:36:17

标签: r ggplot2 rlang

这来自我问recently的另一个问题。据我了解,{{}}中的卷曲rlang用于函数内并与unquoted变量一起使用,因此以下函数和调用有效:

library(ggplot2)
library(tidyverse)
library(cowplot)
library(gridExtra)

#plot function
plot_f <- function(df, x_var, y_var) {
  ggplot(df, aes(x = {{x_var}}, y = {{y_var}})) + geom_boxplot(aes(fill = {{x_var}})) +
    theme_cowplot() 
}

#pass unquoted variable
plot_f(diamonds, cut, depth)  #plots fine

enter image description here

我的问题是,当我取消引用要循环遍历的变量时,为什么以下内容不起作用?

#variables to cycle through
vars1 <- c("cut", "color", "clarity")

#unquoted variables
vars <- noquote(vars1)
vars
#[1] cut     color   clarity

plot_list <- vars %>% 
  map(., ~plot_f(diamonds, .x, depth))

#plots but fill isn't correct
grid.arrange(grobs = plot_list, ncol = 1)

enter image description here

(输出应该是三个不同的图,第一个图看起来像第一个示例中的图。)

1 个答案:

答案 0 :(得分:1)

非标准评估很棘手。这里的关键是需要一个符号列表,而不是一个字符向量,然后还需要在!!调用中使用bang-bang运算符(map()),因为您要捕获值.x,而不是.x本身。

library(tidyverse)
library(cowplot)
library(gridExtra)
library(rlang)

#plot function
plot_f <- function(df, x_var, y_var) {
  ggplot(df, aes(x = {{x_var}}, y = {{y_var}})) + geom_boxplot(aes(fill = {{x_var}})) +
    theme_cowplot() 
}

#variables to cycle through
vars1 <- c("cut", "color", "clarity")
# convert to symbols
vars <- syms(vars1)

# note the !! in front of .x
plot_list <- vars %>% 
  map(., ~plot_f(diamonds, !!.x, depth))

grid.arrange(grobs = plot_list, ncol = 1)

请注意,noquote()输出一个字符串(仅属于'noquote'类),但是您需要一个符号列表。

vars <- noquote(vars1)
str(vars)
#>  'noquote' chr [1:3] "cut" "color" "clarity"

vars <- syms(vars1)
str(vars)
#> List of 3
#>  $ : symbol cut
#>  $ : symbol color
#>  $ : symbol clarity
相关问题