1

I am writing a function that feeds an extra argument to a function if certain condition is met otherwise leave that argument as empty.

The code below is an example that plots "Sepal.Length" and if fn_y is not NULL then the color argument will be feed into the function as well (i.e. split the scatter plot according to fn_y ).

fn_plotly <- function(fn_data, fn_x, fn_y){
  if(is.null(fn_y)){
      p <- plotly::plot_ly(data = fn_data, x = ~fn_data[[fn_x]], 
                           type = "scatter")
  } else {
      p <- plotly::plot_ly(data = fn_data, x =~ fn_data[[fn_x]], 
                           type = "scatter", color = fn_data[[fn_y]])
  }
  return(p)
}

fn_plotly(iris, "Sepal.Length", NULL)
fn_plotly(iris, "Sepal.Length", "Species")

The code above does work but I was wondering if there is any other way that could use pipe function %>% to write the code a bit shorter, i.e. something like this

plotly::plot_ly(data = fn_data, x =~ fn_data[[fn_x]],type="scatter") %>% ifelse(is.null(fn_y),"",color = fn_data[[fn_y]] )

I would like to use this functionality not only on plotly so please do not suggest me to use other plotting packages.

dww
  • 30,425
  • 5
  • 68
  • 111
Daves
  • 175
  • 1
  • 10
  • 2
    Possible duplicate of [Passing in optional arguments to function in r](https://stackoverflow.com/questions/52771479/passing-in-optional-arguments-to-function-in-r) – dww Mar 10 '19 at 02:04
  • 1
    also https://stackoverflow.com/questions/28370249/correct-way-to-specifiy-optional-arguments-in-r-functions – dww Mar 10 '19 at 02:04

1 Answers1

0

Are you aware that you can get the same result without any if then else?

See this:

fn_plotly<-function(fn_data,fn_x,fn_y){


    p<-plotly::plot_ly(data = fn_data, x =~ fn_data[[fn_x]],type="scatter", color=fn_data[,fn_y])

  return(p)

}

fn_plotly(iris,"Sepal.Length",NULL)
fn_plotly(iris,"Sepal.Length","Species")
LocoGris
  • 4,432
  • 3
  • 15
  • 30
  • 1
    This is a reasonable approach for the example OP gave. But I also got the impression that the question was intended to be about how to pass on potentially missing arguments in general. With the plotly function just an example of how this might be used – dww Mar 10 '19 at 02:08
  • 1
    Thanks Johnny for your answer I didn't realize simply passing empty color argument would work but as dww mentioned my main aim was to look at how to pass empty argument and I guess his link to ellipsis(...) is my answer. – Daves Mar 11 '19 at 07:41
  • Indeed, It is the most correct answer. I took too literally your question! – LocoGris Mar 11 '19 at 07:54