I’m using the ‘caret’ library to to do some cross validation on some trees.
The library provides a function called train, that takes in a named argument “method”. Via its ellipsis it’s supposed to let other arguments fall through to another function that it calls. This other function (rpart) takes an argument of the same name, “method”.
Therefore I want to pass two arguments with the same name… and it’s clearly failing. I tried to work around things as shown below but I get the error:
“Error in train.default(x = myx, y = myy, method = “rpart2”, preProcess = NULL, :
formal argument “method” matched by multiple actual arguments”
any help is much appreciated! thanks!
train.wrapper = function(myx, myy, mytrControl, mytuneLenght, ...){
result = train(
x=myx,
y=myy,
method="rpart2",
preProcess=NULL,
...,
weights=NULL,
metric="Accuracy",
trControl=mytrControl,
tuneLength=mytuneLenght
)
return (result)
}
dtree.train.cv = train.wrapper(training.matrix[,2:1777],
training.matrix[,1],
2, method="class")
Here’s a mock-up of your problem with a
tr(train) function that calls anrp(rpart) function, passing it...:What magic is this? And why does the last case actually work?! Well, we need to understand how argument matching works in R. A function
f <- function(foo, bar)is said to have formal parameters “foo” and “bar”, and the callf(foo=3, ba=13)is said to have (actual) arguments “foo” and “ba”.R first matches all arguments that have exactly the same name as a formal parameter. This is why the first “method” argument gets passed to
train. Two identical argument names cause an error.Then, R matches any argument names that partially matches a (yet unmatched) formal parameter. But if two argument names partially match the same formal parameter, that also causes an error. Also, it only matches formal parameters before
.... So formal parameters after...must be specified using their full names.Then the unnamed arguments are matched in positional order to the remaining formal arguments.
Finally, if the formal arguments include
..., the remaining arguments are put into the....PHEW! So in this case, the call to
trfully matchesmethod, and then pass the rest into.... Whentrthen callsrp, themethoargument partially matches its formal parametermethod, and all is well!…Still, I’d try to contact the author of
trainand point out this problem so he can fix it properly! Since “rpart” and “rpart2” are supposed to be supported, he must have missed this use case!I think he should rename his
methodparameter tomethod.or similar (anything longer than “method”). This will still be backward compatible, but allows anothermethodparameter to be passed correctly torpart.