问题描述
如何将可选参数传递给 R 中的函数?
How do I pass in optional arguments to a function in R?
这方面的一个例子是,我可能希望从模型的特定超参数组合中创建一个函数.但是,我不想配置所有超参数,因为在大多数情况下许多超参数都不相关.
An example of this is I might want to be make a function out of a certain combination of hyperparameters for a model. However, I don't want to configure ALL of the hyperparameters as many aren't relevant in most scenarios.
有时我希望能够手动传入我想更改的一个超参数.我经常在函数中看到 ...,但无法弄清楚这是否与这种情况有关,或者至少如何使用它们.
From time to time I would like to be able to manually pass in that one hyper-parameter I'd like to change. I often see the ... in functions, but can't figure out if that is relevant to this situation or at least how to use them.
library(gbm)
library(ggplot)
data('diamonds', package = 'ggplot2')
example_function = function(n.trees = 5){
model=gbm(formula = price~ ., n.trees = 5, data = diamonds)
}
# example of me passing in an unplanned argument
example_function(n.trees = 5, shrinkage = 0.02)
这是否可以以智能方式处理?
Is this possible to handle in an intelligent way?
推荐答案
您可以使用 ...
参数(记录在 ?dots
中)从一个调用函数.在你的情况下,试试这个:
You can use the ...
argument (documented in ?dots
) to pass down arguments from a calling function. In your case, try this:
library(gbm)
library(ggplot2)
data('diamonds', package = 'ggplot2')
example_function <- function(n.trees = 5, ...){
gbm(formula = price~ ., n.trees = 5, data = diamonds, ...)
}
# Pass in the additional 'shrinkage' argument
example_function(n.trees = 5, shrinkage = 0.02)
## Distribution not specified, assuming gaussian
## gbm(formula = price ~ ., data = diamonds, n.trees = 5, shrinkage = 0.02)
## A gradient boosted model with gaussian loss function.
## 5 iterations were performed.
There were 9 predictors of which 2 had non-zero influence.
这篇关于将可选参数传递给 r 中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!