library(ggplot2)
library(dplyr)
# Opt 1 - specify a default; not viable in my actual problem due to lack of default
fun_default <- function(df, x, y, color="red"){
p <- df %>%
ggplot(aes({{x}}, {{y}})) +
geom_point(color=color)
p
}
# Opt 2 - use an if statement for the whole argument
# workable but cumbersome in my actual problem, since I'd have to repeat the if/else multiple times throughout the code
fun_if <- function(df, x, y, color=NULL){
p <- df %>%
ggplot(aes({{x}}, {{y}})) +
{if(is.null(color)) { geom_point() }
else { geom_point(color = color)}}
p
}
fun_default(mtcars, wt, mpg, color="blue")
fun_if(mtcars, wt, mpg, color="blue")
fun_if(mtcars, wt, mpg)
我想做的是嵌套if语句内侧
geom_point呼叫,或者设置一个颜色参数,该颜色参数将默认为GGPLOT的任何默认值,而无需我自己指定默认值。 在我的脑海中,这看起来像以下内容之一(显然这些实际上都没有用):# if statement inside of geom_point()
fun_wish1 <- function(df, x, y, color=NULL){
p <- df %>%
ggplot(aes({{x}}, {{y}})) +
geom_point( {if(!is.null(color)) {color=color}} )
p
}
# somehow tell geom_point to ignore color or use its default for color
fun_wish2 <- function(df, x, y, color=NULL){
if(is.null(color)) {color = NA}
p <- df %>%
ggplot(aes({{x}}, {{y}})) +
geom_point(color=color)
p
}
仔细考虑
ellipsis构造用于传递可变数量的参数: