将可选参数传递给r中的函数

时间:2018-10-12 02:48:30

标签: r function arguments

如何将可选参数传递给R中的函数?
这方面的一个例子是,我可能想根据模型的超参数的某种组合来构造函数。但是,我不想配置所有的超参数,因为在大多数情况下,其中的许多都不相关。

我希望能够不时手动传递我想更改的那个超参数。我经常在函数中看到...,但无法弄清楚这是否与这种情况有关,或者至少与如何使用它们有关。

@ProjectID

这有可能以一种智能的方式处理吗?

2 个答案:

答案 0 :(得分:3)

您可以使用...参数(记录在?dots中)从调用函数中传递参数。您可以尝试以下方法:

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.

答案 1 :(得分:0)

使用点符号:

sample<-function(default = 5, ...){
                 print(paste(default, ... ))
                 }
> sample(5)
[1] "5"
> sample(10, other = 5)
[1] "10 5"
相关问题