我想创建一个生成ggplot图的函数,并为方面变量提供可选参数facet_grid()。
特别是,如果可能的话,我想纳入条件逻辑里面 facet_grid。我也想使用整洁的评估框架-所以没有公式字符串!
但是,我所有的尝试都失败了。
library(tidyverse)
iris <- iris %>% add_column(idx = rep(1:2, 75))
Run Code Online (Sandbox Code Playgroud)
我的第一次尝试失败,因为facet_grid试图找到一个名为NULL(带有反引号)的变量。
plot_iris <- function(df_in, facet_var = NULL){
ggplot(df_in) +
geom_point(aes(Sepal.Length, Sepal.Width)) +
facet_grid(vars(!!enquo(facet_var)), vars(idx))
}
plot_iris(iris)
#> Error: At least one layer must contain all faceting variables: `NULL`.
#> * Plot is missing `NULL`
#> * Layer 1 is missing `NULL`
Run Code Online (Sandbox Code Playgroud)
plot_iris(iris, Species)但是,运行正常。
我的第二次尝试也失败了,但是有不同的错误消息。
plot_iris2 <- function(df_in, facet_var = NULL){
facet_quo <- enquo(facet_var)
ggplot(df_in) …Run Code Online (Sandbox Code Playgroud)