[英]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.