rfunctionellipsisrpart

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

Solution

  • 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.