问题描述
如何将可选参数传递给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中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!