Home > database >  How to set aliases for function arguments in an R package?
How to set aliases for function arguments in an R package?

Time:01-10

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?

CodePudding user response:

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.

  •  Tags:  
  • Related