Happy Thursday everyone!
I have a simple tidy evaluation example in which columns from a data frame are passed to a ggplot
function. Can anyone tell me why example #1 failed but #2 and #3 worked?
Thanks!
library(rlang)
library(dplyr)
library(purrr)
library(ggplot2)
Sample data
set.seed(1)
df <- tibble(a = rnorm(30), b = rnorm(30), c = rnorm(30))
Example 1: Not ok (note what happened to purrr::map
and ensym
)
my_plot_ensym <- function(df, var_x, var_y)
{
var_x <- ensym(var_x)
var_y <- ensym(var_y)
cat('\nThis is what happens behind the scene: \n')
qq_show(
ggplot(df, aes(x = !!var_x, y = !!var_y)) + geom_point()
)
plot1 <- ggplot(df, aes(x = !!var_x, y = !!var_y)) + geom_point()
return(plot1)
}
input_x <- names(df)[-1]
str(input_x)
#> chr [1:2] "b" "c"
p1 <- input_x %>% map(., ~ my_plot_ensym(df, .x, "a"))
#>
#> This is what happens behind the scene:
#> ggplot(df, aes(x = .x, y = a)) + geom_point()
#>
#> This is what happens behind the scene:
#> ggplot(df, aes(x = .x, y = a)) + geom_point()
# p1 <- input_x %>% lapply(., function(x) {my_plot_ensym(df, .x, "a")})
p1[[1]]
#> Error in FUN(X[[i]], ...): object '.x' not found
Example 2: OK after adding is.character()
test
my_plot_mod <- function(df, var_x, var_y)
{
if (is.character(var_x) && is.character(var_y)) {
var_x <- ensym(var_x)
var_y <- ensym(var_y)
}
cat('\nThis is what happens behind the scene: \n')
qq_show(
ggplot(df, aes(x = !!var_x, y = !!var_y)) + geom_point()
)
plot1 <- ggplot(df, aes(x = !!var_x, y = !!var_y)) + geom_point()
return(plot1)
}
input_x <- names(df)[-1]
p2 <- input_x %>% map(., ~ my_plot_mod(df, .x, "a"))
#>
#> This is what happens behind the scene:
#> ggplot(df, aes(x = b, y = a)) + geom_point()
#>
#> This is what happens behind the scene:
#> ggplot(df, aes(x = c, y = a)) + geom_point()
p2[[2]]
Example 3: Also ok after replacing ensym
with sym
my_plot_sym <- function(df, var_x, var_y)
{
var_x <- sym(var_x)
var_y <- sym(var_y)
cat('\nThis is what happens behind the scene: \n')
qq_show(
ggplot(df, aes(x = !!var_x, y = !!var_y)) + geom_point()
)
plot1 <- ggplot(df, aes(x = !!var_x, y = !!var_y)) + geom_point()
return(plot1)
}
p3 <- input_x %>% map(., ~ my_plot_sym(df, .x, "a"))
#>
#> This is what happens behind the scene:
#> ggplot(df, aes(x = b, y = a)) + geom_point()
#>
#> This is what happens behind the scene:
#> ggplot(df, aes(x = c, y = a)) + geom_point()
p3[[1]]