gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:56:15 25 4
gpt4 key购买 nike

如何将可选参数传递给 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)

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

最佳答案

您可以使用 ... 参数(记录在 ?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.

关于r - 将可选参数传递给 r 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52771479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com