[英]How to set aliases for function arguments in an R package?
我正在 R 中开发一个相对简单的 package,其中包含几个可视化功能。 现在我有一个名为make_a_bargraph()
的 function ,它有一个colour
参数。 我想要的是它也接受color
(使用美式拼写)作为有效参数。 所以基本上就像ggplot
一样,它的 geoms 也是如此。
理想情况下,我们会有一个 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
一个 go 将如何实现这一目标?
一种方法是在您的 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"
您还可以查看ggplot2::standardise_aes_names
及其周围,了解ggplot2
是如何做到的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.