简体   繁体   中英

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. Now I have a function called for example make_a_bargraph() which has a colour argument. What I want is for it to also accept color (with the American spelling) as a valid argument. so basically like ggplot also does with its geoms.

Ideally we would have a function like:

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?

One way is by using ... in your function declaration:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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