3

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
Tomas Greif
  • 21,685
  • 23
  • 106
  • 155

3 Answers3

4

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.

tonytonov
  • 25,060
  • 16
  • 82
  • 98
0

this might work for you

a <- function(df, cp = NULL, minbucket = NULL, ...) {
  if (is.null(cp)) cp <- 0.001
  if (is.null(minbucket)) minbucket <- nrow(df) / 20

  rpart.control(cp = cp, minbucket = minbucket, ...)  
}

good source for more infos (Advanced R by Hadley Wickham) http://adv-r.had.co.nz/Functions.html

ckluss
  • 1,477
  • 4
  • 21
  • 33
0

Had a similar question, and wonder whether this is not a simpler way, following the modified example of tonytonov:

b2 <- function(df, cp=1, minbucket=2, ...) { 
  print_all(cp=cp, minbucket=minbucket, ...)
}
   
print_all <- function(cp=cp, minbucket=minbucket, ...) {
  print(paste(cp, minbucket))
  print(list(...))     
}

Basically, the default values can be overwritten also by the ... arguments. Am I missing something, or is this now only possible with R having developed further during the last 6 years?

MR_MPI-BGC
  • 265
  • 3
  • 11