问题
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 arguement
example_function(n.trees = 5, shrinkage = 0.02)
Is this possible to handle in an intelligent way?
回答1:
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.
回答2:
Using dot notation:
sample<-function(default = 5, ...){
print(paste(default, ... ))
}
> sample(5)
[1] "5"
> sample(10, other = 5)
[1] "10 5"
来源:https://stackoverflow.com/questions/52771479/passing-in-optional-arguments-to-function-in-r