3

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

到目前为止,我还没有成功 - 请参阅下面的草稿。目前该功能抱怨没有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
4

3 回答 3

4

这是对您的功能的一个小修正: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(...))
}

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

于 2015-01-11T08:44:47.727 回答
0

这可能对你有用

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, ...)  
}

更多信息的好来源(Hadley Wickham 的 Advanced R) http://adv-r.had.co.nz/Functions.html

于 2015-01-11T08:48:11.543 回答
0

有一个类似的问题,想知道这是否不是更简单的方法,遵循 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(...))     
}

基本上,默认值也可以被...参数覆盖。我是否遗漏了什么,或者现在只有 R 在过去 6 年中进一步发展才有可能?

于 2021-11-29T10:24:18.007 回答