简体   繁体   English

如何在 R ZEFE90A8E604A7C840E88D03A7DZ 中为 function arguments 设置别名?

[英]How to set aliases for function arguments in an R package?

I am developing a relatively simple package in R containing a couple of visualization functions.我正在 R 中开发一个相对简单的 package,其中包含几个可视化功能。 Now I have a function called for example make_a_bargraph() which has a colour argument.现在我有一个名为make_a_bargraph()的 function ,它有一个colour参数。 What I want is for it to also accept color (with the American spelling) as a valid argument.我想要的是它也接受color (使用美式拼写)作为有效参数。 so basically like ggplot also does with its geoms.所以基本上就像ggplot一样,它的 geoms 也是如此。

Ideally we would have a function like:理想情况下,我们会有一个 function 像:

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

How would one go about achieving this?一个 go 将如何实现这一目标?

One way is by using ... in your function declaration:一种方法是在您的 function 声明中使用...

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"

You can also look at ggplot2::standardise_aes_names and around it to see how ggplot2 does it.您还可以查看ggplot2::standardise_aes_names及其周围,了解ggplot2是如何做到的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM