问题
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:
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]]
来源:https://stackoverflow.com/questions/34678882/creating-a-loop-for-different-random-forest-training-algorithms