Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass arguments to function using ellipsis and set default for some if not existing

I have a main function which passes arguments to another function which uses rpart to generate model. I would like to have the possibility to specify rpart.control from main function using ellipsis. In case when no cp or minbucket is defined, then I would like to use my default values for these two parameters.

So far, I was not successful - see my draft below. Currently the function is complaining that no cp is found. I understand why, but cannot figure out, how to apply defaults if user did not provide own controls.

require(rpart)

a <- function(df, ...) {
  b(df, ...)
}

b <- function(df, ...) {
  if (is.null(cp)) cp <- 0.001 
  if (is.null(minbucket)) minbucket = nrow(df) / 20
  rcontrol <- rpart.control(cp = cp, minbucket = minbucket, ...)
  rcontrol
}


a(iris) # no controls set my defaults for cp and minbucket
a(iris, cp = 0.123) # set cp, use my default for minbucket
a(iris, cp = 0.123, minbucket = 100) # set cp, and minbucket
a(iris, maxcompete = 3) # use my defaults for cp and minbucket, but pass maxcompete
like image 449
Tomas Greif Avatar asked Dec 20 '25 21:12

Tomas Greif


1 Answers

Here's a small correction to your function: apply list(...) first.

b <- function(df, ...) {
  l <- list(...)
  if (is.null(l$cp)) l$cp <- 1
  if (is.null(l$minbucket)) l$minbucket <- 2
  print_all(l$cp, l$minbucket, ...)
}

print_all <- function(...) {
  print(list(...))
}

Run your examples to make sure all defaults are set.

like image 56
tonytonov Avatar answered Dec 22 '25 10:12

tonytonov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!