Let's start with some simple code:
require(randomForest)
randomForest(mpg~.,mtcars,ntree=10)
This builds a random forest of 10 trees.
What I want is to store the parameter in a list in than make the function call. Something like this:
require(randomForest)
l<-list(ntree=10)
randomForest(mpg~.,mtcars,l[[1]])
However, this does not work. The error message is:
Error in if (ncol(x) != ncol(xtest)) stop("x and xtest must have same number of columns") : argument is of length zero
This indicates that the parameter xtest=NULL of randomForest is set to 10 instead of ntree.
Why is that? How can I pass the parameter ntree as a list element?
Thank you.
The correct call would be: foo(a=list(1), b=list(2)). If you wanted to pass to your function a single list then you have to declare it as function(a) and then call it the same way you did.
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
14.1 Functions in RFunctions can be passed as arguments to other functions. This is very handy for the various apply functions, like lapply() and sapply() . Functions can be nested, so that you can define a function inside of another function.
We can pass an argument to a function when we call that function. We just need to give the value of the argument inside the parenthesis after the function's name. The following is the example of a function with a single argument. The function takes a numeric input and checks whether it is divisible by 3 or not.
You can use do.call
to accomplish this, although you will have to adjust how you input the arguments.
do.call(randomForest, list(formula=as.formula(mpg~.), data=mtcars, ntree=10))
The printed output is not as pretty, but at the end, you get
Type of random forest: regression
Number of trees: 10
No. of variables tried at each split: 3
Mean of squared residuals: 9.284806
% Var explained: 73.61
and if you save the returned object, it will have the same values as if you typed it in.
You can store the list ahead of time as well
l <- list(formula=as.formula(mpg~.), data=mtcars, ntree=10)
myForest <- do.call(randomForest, l)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With