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

问题描述 投票:0回答:2

如何将可选参数传递给 R 中的函数?

举个例子,我可能想用模型的特定超参数组合来创建一个函数。但是,我不想配置所有超参数,因为许多超参数在大多数情况下都不相关。

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

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)

这可以通过智能方式处理吗?

r function arguments
2个回答
8
投票

您可以使用

...
参数(在
?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
投票

使用点符号:

sample<-function(default = 5, ...){
                 print(paste(default, ... ))
                 }
> sample(5)
[1] "5"
> sample(10, other = 5)
[1] "10 5"
© www.soinside.com 2019 - 2024. All rights reserved.