R 使用省略号将参数传递给函数,并为某些参数设置默认值(如果不存在)
我有一个主函数,它将参数传递给另一个函数,该函数使用R 使用省略号将参数传递给函数,并为某些参数设置默认值(如果不存在),r,function,ellipsis,rpart,R,Function,Ellipsis,Rpart,我有一个主函数,它将参数传递给另一个函数,该函数使用rpart生成模型。我希望能够使用省略号从主函数指定rpart.control。如果未定义cp或minbucket,则我希望使用这两个参数的默认值 到目前为止,我还没有成功——见下面我的草稿。目前,该函数抱怨未找到cp。我理解为什么,但无法理解,若用户并没有提供自己的控件,如何应用默认值 require(rpart) a <- function(df, ...) { b(df, ...) } b <- function(df
rpart
生成模型。我希望能够使用省略号从主函数指定rpart.control
。如果未定义cp
或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
require(rpart)
下面是对函数的一个小更正:首先应用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(...))
}
b这可能适合你
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, ...)
}
a