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.
我有一个主函数,它将参数传递给另一个函数,该函数使用rpart生成模型。我想有可能指定rpart。用省略号控制主功能。如果没有定义cp或minbucket,那么我想对这两个参数使用默认值。
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.
到目前为止,我还没有成功——请看下面我的草稿。目前函数正在抱怨没有找到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
2 个解决方案
#1
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.
运行示例,确保设置了所有默认值。
#2
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
获取更多信息的好来源(哈德利·韦翰的高级R) http://adv-r.had.co.nz/Functions.html
#1
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.
运行示例,确保设置了所有默认值。
#2
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
获取更多信息的好来源(哈德利·韦翰的高级R) http://adv-r.had.co.nz/Functions.html