在自定义函数内部通过可选参数到GGPLOT

问题描述 投票:0回答:1
这里是有效两种方法的一个非常基本的例子:

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构造
用于传递可变数量的参数:
r function ggplot2 optional-parameters
1个回答
0
投票
fun_default <- function(df, x, y, ...){ p <- df %>% ggplot(aes({{x}}, {{y}})) + geom_point(...) p }

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.