Creating a loop for different random forest traini

2019-09-02 20:39发布

Im trying to write a for loop to create various random forest models. I've stored the variables I would like to use in the different models in a list called list:

 list <- c("EXPG1 + EXPG2", "EXPG1 + EXPG2 + distance")

Then I try to loop over it created predictions. What I finally want to achieve is this:

modFit1 <- train(won ~ EXPG1 + EXPG2, data=training, method="rf", prox=TRUE)
modFit2 <- train(won ~ EXPG1 + EXPG2 + distance, data=training, method="rf", prox=TRUE)

I have some issues trying to accomplish this however.

This doesn't work:

modFit1 <- train(won ~ list[1], data=training, method="rf", prox=TRUE)

And also this doesnot seem to do the trick:

for (R in modfits) {

  modfit <- paste0("won ~ ", R, ", data=training, method=\"rf\", prox=\"TRUE")
 train(modfit)

}

Any thoughts on what goes wrong?

1条回答
成全新的幸福
2楼-- · 2019-09-02 21:00

Create an empty list to store the model in first

results <- vector('list',2)
list <- c("EXPG1 + EXPG2", "EXPG1 + EXPG2 + distance")

for (i in 1:2){
  results[i] <- train(won ~ list[i], data=training, method="rf", prox=TRUE)
}

Then you should be able to call predict on results[[1]]

查看更多
登录 后发表回答