6

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.

Funkwecker
  • 766
  • 13
  • 22

1 Answers1

7

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)
lmo
  • 37,904
  • 9
  • 56
  • 69