我正在用 R 開發一個相對簡單的包,其中包含幾個可視化功能。現在我有一個名為 example 的函式,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
如何實作這一目標?
uj5u.com熱心網友回復:
一種方法是...在函式宣告中使用:
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做的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409635.html
標籤:
