【问题标题】:How to set aliases for function arguments in an R package?如何为 R 包中的函数参数设置别名?
【发布时间】:2022-01-10 20:55:23
【问题描述】:

我正在用 R 语言开发一个相对简单的包,其中包含几个可视化功能。现在我有一个名为 make_a_bargraph() 的函数,它有一个 colour 参数。我想要的是它也接受color(使用美式拼写)作为有效参数。所以基本上就像ggplot 一样,它的geoms 也是如此。

理想情况下,我们应该有这样的函数:

make_a_bargraph <- function(colour) {
  #' @desc function to do something with the colour-argument
  #' @param colour the colour to be printed
  #' @return a printed string

  print(colour)
}

# with the 'regular' call:
make_a_bargraph(colour = "#FF0000")

# and the desired output:
[1] FF0000

# but also this possibility with US spelling:
make_a_bargraph(color = "#FF0000")

# and the same desired output:
[1] FF0000

如何实现这一目标?

【问题讨论】:

    标签: r function ggplot2 colors package


    【解决方案1】:

    一种方法是在函数声明中使用...

    make_a_bargraph <- function(colour, ...) {
      dots <- list(...)
      if ("color" %in% names(dots)) {
        if (missing(colour)) {
          colour <- dots[["color"]]
        } else {
          warning("both 'colour=' and 'color=' found, ignoring 'color='")
        }
      }
      print(colour)
    }
    
    make_a_bargraph(colour="red")
    # [1] "red"
    make_a_bargraph(color="red")
    # [1] "red"
    make_a_bargraph(colour="blue", color="red")
    # Warning in make_a_bargraph(colour = "blue", color = "red") :
    #   both 'colour=' and 'color=' found, ignoring 'color='
    # [1] "blue"
    

    您还可以查看ggplot2::standardise_aes_names 及其周围,了解ggplot2 是如何做到的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-19
      • 2012-02-22
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      相关资源
      最近更新 更多