Reputation: 363
I have two lists
a=expand.grid(mtry=c(8))
b=expand.grid(usekernel=c(8), fL=c(9))
c=expand.grid(usekernel=c(8), fL=c(9))
list_1<- list(a,b,c)
list_2<- list("rf","nb","nb2")
And I have a function as follows
func(TrainData, TrainClasses,method,tune)
if method is "rf" then tune=a, if "nb" then tune=b, nb2=c
Instead of writing the method and tune every time, I want to pass the lists(list_1 and list_2) and invoke the "func" function for every method. I tried for loop, but its not giving the desired results.
Reproducible code
library(caret)
data(iris)
TrainData <- iris[,1:4]
TrainClasses <- iris[,5]
method<- c("rf")
tune<-expand.grid(mtry=c(8))
func<- function(TrainData, TrainClasses,method,tune )
{
k <- train(TrainData, TrainClasses,
method = method,
preProcess = c("center", "scale"),
tuneLength = 10,
tuneGrid = tune,
trControl = trainControl(method = "cv"))
k
}
func(TrainData, TrainClasses,method, tune)
So, in the above function, I'm passing one method and its tune, but now I want to pass the list of methods one after the other with their respective tune instead of giving method and its tune every time, I want to execute all the 3 methods at once. Like I said before, my list_2 contains methods and list_1 contains respective tunes.
My code:
for(i in 1:3){
tune_e=c(list(TrainData=TrainData,TrainClasses=TrainClasses),list_2[i],list_1[i])
do.call('func',tune_e)
}
Upvotes: 2
Views: 2675
Reputation: 1809
Excuse me if I haven't quite grasped what you want. Would this work?
list_1 <- c(a,b,c); list_2 <- c("rf","nb","nb2")
for(i in 1:3){
func(TrainData, TrainClasses, list_2[i], list_1[i])
}
The problem is with the lists. If they are simply vectors, then it should work. Do they need to be lists for another reason? If so:
list_1 <- list(a,b,c); list_2 <- list("rf","nb","nb2")
for(i in 1:3){
func(TrainData, TrainClasses, list_2[[1]][i], list_1[[1]][i])
}
The double square brackets are important.
Upvotes: 2