是否可以创建一个包含无意义参数的列表,例如列表中的
fill.var
design <- list( geom_boxplot(aes(fill=fill.var), na.rm=TRUE), theme(plot.title = element_text(size = 20, face = "bold"), legend.position = "bottom"), )
,然后在函数中将此参数作为参数赋予意义,如下所示:
general_plot <- function(df,x.var,y.var,fill.var){
ggplot(data=df, aes(x={{x.var}}, y={{y.var}}, fill={{fill.var}}))+design
}
plot_generator(subset_table,treatment,size,treatment)
当我尝试这样写时,运行该函数时出现错误,提示“
object `fill.var` not found
”,当我尝试“design<-list(geom_boxplot(aes(fill=!fill.var)))
”时也是如此。
当我尝试 design<-list(geom_boxplot(aes(fill=!!fill.var)))
和 design<-list(geom_boxplot(aes(fill={{fill.var}})))
时,在尝试在函数中使用 design
对象之前,我收到了错误。
我更愿意这样解决它,但我也可以创建一个默认的
fill.var
并从函数参数中超出它,我不知道如何...
tnx!
我认为您正在寻找 quasiquotation 与 tidyevaluation:
!!
bang bang operator
sym()
将变量名称从字符串转换为符号。
!!
取消引用符号,以便 ggplot 将它们识别为列名称
library(ggplot2)
library(rlang)
general_plot <- function(df, x.var, y.var, fill.var) {
# Creating symbols
x.var <- sym(x.var)
y.var <- sym(y.var)
fill.var <- sym(fill.var)
design <- list(
geom_boxplot(aes(fill = !!fill.var), na.rm = TRUE),
theme(plot.title = element_text(size = 20, face = "bold"), legend.position = "bottom")
)
ggplot(data = df, aes(x = !!x.var, y = !!y.var)) + design
}
general_plot(diamonds, "cut", "price", "color")
{{}}
curly curly
library(ggplot2)
library(rlang)
general_plot <- function(df, x.var, y.var, fill.var) {
design <- list(
geom_boxplot(aes(fill = {{ fill.var }}), na.rm = TRUE),
theme(plot.title = element_text(size = 20, face = "bold"), legend.position = "bottom")
)
ggplot(data = df, aes(x = {{ x.var }}, y = {{ y.var }})) + design
}
general_plot(diamonds, cut, price, color)