I want to train several models with caret
package (one for each of the 7 response variables) within a loop for.
My data.frame data
has 46 predictors (all of them are used to train all models) and 7 responses.
Some Rcode I tried but it failed:
models.list = list()
Ynames = names(data)[47:ncol(data)]
for(y in Ynames)
{
models.list[[y]] = train(as.name(y)~., subset(data,select=-Ynames[-y]),method="".....)
}
My variable Ynames
contains all the responses.
Each model must be trained with a single response variable.
So for iteration 1, we would train the model for Ynames[1]
response and all 46 predictors, but it's necessary to exclude from the dataset data
all non-first response variables (Ynames[-1]
).
This might be an alternative which matches your example (using iris). The subsetting was based on this post: removing a list of columns from a data.frame using subset
models.list = list()
Ynames = names(iris)[3:ncol(iris)]
for(y in Ynames)
{
to.remove <- Ynames[!Ynames==y]
`%ni%` <- Negate(`%in%`)
models.list[[y]] = train(as.name(y)~., subset(iris,select = names(iris) %ni% to.remove),method="".....)
}