Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - passing unquoted variables to curly curly {{}} ggplot function

This comes from a different question I asked recently. As I understand curly curly {{}} from rlang is used within functions and with unquoted variables so the following function and call works:

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

My question is why does the following not work when I unquote the variables I want to cycle through?

#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

(The output should be three different plots, with the first one looking like the plot from the first example.)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Nonstandard evaluation is tricky. The key here is that you need a list of symbols, not a character vector, and then you also need to use the bang-bang operator (!!) in your map() call because you want to capture the value of .x, not .x itself.

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)

Note that noquote() outputs a character string (just of class 'noquote'), but you need a list of symbols.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...