如果R

时间:2019-03-10 01:22:56

标签: r arguments plotly

我正在编写一个函数,如果满足某些条件,该函数将向函数提供额外的参数,否则将该参数保留为空。

下面的代码是绘制“ Sepal.Length”的示例,如果fn_y不是NULL,则color参数也将被馈送到函数中(即,根据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")

上面的代码确实有效,但是我想知道是否还有其他方法可以使用管道函数%>%来编写短一些的代码,即类似这样的

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

我不仅想在绘图上使用此功能,所以请不要建议我使用其他绘图软件包。

0 个答案:

没有答案