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

nwwlzxa7  于 5个月前  发布在  其他
关注(0)|答案(2)|浏览(63)

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

字符串
这是否可能以一种智能的方式处理?

jc3wubiy

jc3wubiy1#

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

字符串

bxpogfeg

bxpogfeg2#

使用点表示法:

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

字符串

相关问题