R enum-alike argument with match.arg: How to choose a non-first element as default value?

Viewed 300

How can I declare another than the first of multiple allowed argument values as default value (if no value was passed in)?

library(stats)

center <- function(x, type = c("mean", "median", "trimmed")) {
  type <- match.arg(type)
  switch(type,
         mean = mean(x),
         median = median(x),
         trimmed = mean(x, trim = .1))
}

values <- c(100, 120, 200)

center(values, "median")
# [1] 120

center(values, "mean")
# [1] 140

# uses the first value "mean" as the default!
center(values)  
# [1] 140

I would like to see the default value in the function signature if possible in order to make the default value explicit (visible), e. g. (non-working pseudo-code!) to make the second element the default value:

center <- function(x, type = c("mean", "median", "trimmed")[2]) {...

Other proposals are also welcome!

PS: I could put the default value always in the first position but if there is a logical order in the list I would prefer to keep it (e. g. payment.frequency = c("monthly", "quarterly", "semi-annually", "annually").

2 Answers
Related