I want to train n random forest on different samples. sample 1 gives rf1, sample 2 gives rf2, etc.
BUT this kind of code doesn't work (error object of type 'closure' is not subsettable)
for (i in 1:3) {
rf$i <- train(Y~.,data=trainingData,method="rf",
ntree = 100,
tuneGrid=data.frame(mtry = mtry),
trControl = controle,
metric='ROC')
}
How can I create the n random forest models? Yours sincerely Loïc
It does not work because rf
does not exist yet and you can't subset it.
1. Use a list as a container
The following should work.
# define the length of your random forest trials
N = 3
rf = vector( "list", N)
for (i in seq_len( N ) {
rf[[ i ]] <- train( Y ~. , data = trainingData, method = "rf",
ntree = 100,
tuneGrid=data.frame(mtry = mtry),
trControl = controle,
metric='ROC')
}
The above code stores a list rf
which contains three element according to N
. You can access to each object with rf[[ 1 ]]
, rf[[ 2 ]]
, rf[[ 3 ]]
.
2. Store objects independently
If you want to physically store independent rf
objects in your Global Enviroment, the you have to use assign()
as follows:
# define the length of your random forest trials
N = 3
for (i in seq_len( N ) {
assign( paste0( "rf", i) ,
train( Y ~. ,
data = trainingData, method = "rf",
ntree = 100,
tuneGrid=data.frame(mtry = mtry),
trControl = controle,
metric='ROC')
}
This stores three objects rf1
, rf2
, and rf3
in your environment and you can work on them independently.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.