如何为R包中的函数参数设置别名



我正在R中开发一个相对简单的包,其中包含几个可视化函数。现在我有一个函数,例如make_a_bargraph(),它有一个colour参数。我想要的是它也接受color(美国拼写(作为一个有效的参数。所以基本上像CCD_ 4一样也处理它的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

如何实现这一目标?

一种方法是在函数声明中使用...
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是如何做到这一点的

最新更新