【问题标题】:Wrapper function for R with optional parameter [duplicate]带有可选参数的 R 包装函数 [重复]
【发布时间】:2017-11-12 23:44:54
【问题描述】:

我有以下包装函数:

plot.histogram = function(x.var, y.var, pf) {
  ggplot(aes_string(x.var, y.var), data = pf) +
    geom_bar(stat="identity", color = "black", fill = "steelblue") 
} 

该功能运行良好。但是,有时我不想通过 y.var 而只是在 y 轴上使用默认的 count。因此,在这种特定情况下,图表不应该是条形图,而是直方图。因此,根据y.var 的缺失,该函数应自动决定是绘制条形图还是直方图。

那么,如果没有给出y.var,如何使参数y.var 成为可选参数并自动绘制直方图?

【问题讨论】:

  • 请提供可重现的示例。还有 barplot != histogram,你想要哪个?
  • 你说得对。编辑它:问题现在区分条形图和直方图。我没有添加一个可重复的例子来保持对读者的简短。这更像是一个功能/逻辑问题。

标签: r


【解决方案1】:

如果您设置保留当前参数,我会将y.var 设置为具有NA 的初始值,然后将其传递。在初始设置对象p 之后,您可以稍后简单地传递y.var 参数:

plot.histogram = function(x.var, y.var = NA, pf) {
  p = ggplot(aes_string(x.var), data = pf)
  if(is.na(y.var) == TRUE){
    p + geom_histogram()
  }  
  else{
    p + geom_bar(aes_string(y = y.var),stat="identity", color = "black", fill = "steelblue")
  }
}

【讨论】:

  • 这正是我所需要的。谢谢!
  • 使用 is.na() 时不需要==True
猜你喜欢
  • 1970-01-01
  • 2016-03-27
  • 2021-03-28
  • 2013-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多