如何在for循环中定义模型名称?

问题描述 投票:1回答:1

我想在不同样本上训练n个随机森林。样本1给出rf1,样本2给出rf2,依此类推。

但是这种代码不起作用(类型为'closure'的错误对象不可子集)

for (i in 1:3) {
       rf$i <- train(Y~.,data=trainingData,method="rf",
              ntree = 100,
              tuneGrid=data.frame(mtry = mtry),
              trControl = controle,
              metric='ROC')
}

如何创建n个随机森林模型?此致Loïc

r
1个回答
0
投票

它不起作用,因为rf尚不存在,因此您无法对其进行子集化。

1。使用列表作为容器

以下内容应该起作用。

# 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')
}

以上代码存储列表rf,其中包含根据N的三个元素。您可以使用rf[[ 1 ]]rf[[ 2 ]]rf[[ 3 ]]访问每个对象。

2。独立存储对象

如果要在全局环境中物理存储独立的rf对象,则必须使用assign(),如下所示:

# 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')
    }

这将在环境中存储三个对象rf1rf2rf3,您可以独立地对其进行操作。

© www.soinside.com 2019 - 2024. All rights reserved.