Reputation: 4698
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
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)
(The output should be three different plots, with the first one looking like the plot from the first example.)
Upvotes: 3
Views: 1066
Reputation: 17810
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
Upvotes: 3