使用省略号将参数传递给函数,并为某些参数设置默认值(如果不存在)

Tom*_*eif 3 r function ellipsis rpart

我有一个主函数,它将参数传递给另一个用于生成模型的函数rpart。我希望能够rpart.control使用省略号从主函数中指定。如果没有定义cpminbucket,那么我想使用这两个参数的默认值。

到目前为止,我还没有成功 - 请参阅下面的草稿。目前该函数抱怨没有cp找到。我理解为什么,但无法弄清楚,如果用户没有提供自己的控件,如何应用默认值。

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
Run Code Online (Sandbox Code Playgroud)

ton*_*nov 5

这是对您的函数的一个小修正:list(...)首先应用。

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 Code Online (Sandbox Code Playgroud)

运行您的示例以确保设置了所有默认值。