【问题标题】:Creating a loop using the randomForest() command使用 randomForest() 命令创建循环
【发布时间】:2021-07-25 07:49:58
【问题描述】:

所以我有一个向量向量,称为“公式:包含 31 个潜在模型(1 个输出变量和 5 个潜在解释变量)。


$V1
[1] "Edible ~ CapShape"

$V2
[1] "Edible ~ CapSurface"

$V3
[1] "Edible ~ CapColor"

$V4
[1] "Edible ~ Odor"

$V5
[1] "Edible ~ Height"

$V6
[1] "Edible ~ CapShape + CapSurface"

$V7
[1] "Edible ~ CapShape + CapColor"

$V8
[1] "Edible ~ CapShape + Odor"

$V9
[1] "Edible ~ CapShape + Height"

$V10
[1] "Edible ~ CapSurface + CapColor"

$V11
[1] "Edible ~ CapSurface + Odor"

$V12
[1] "Edible ~ CapSurface + Height"

$V13
[1] "Edible ~ CapColor + Odor"

$V14
[1] "Edible ~ CapColor + Height"

$V15
[1] "Edible ~ Odor + Height"

$V16
[1] "Edible ~ CapShape + CapSurface + CapColor"

$V17
[1] "Edible ~ CapShape + CapSurface + Odor"

$V18
[1] "Edible ~ CapShape + CapSurface + Height"

$V19
[1] "Edible ~ CapShape + CapColor + Odor"

$V20
[1] "Edible ~ CapShape + CapColor + Height"

$V21
[1] "Edible ~ CapShape + Odor + Height"

$V22
[1] "Edible ~ CapSurface + CapColor + Odor"

$V23
[1] "Edible ~ CapSurface + CapColor + Height"

$V24
[1] "Edible ~ CapSurface + Odor + Height"

$V25
[1] "Edible ~ CapColor + Odor + Height"

$V26
[1] "Edible ~ CapShape + CapSurface + CapColor + Odor"

$V27
[1] "Edible ~ CapShape + CapSurface + CapColor + Height"

$V28
[1] "Edible ~ CapShape + CapSurface + Odor + Height"

$V29
[1] "Edible ~ CapShape + CapColor + Odor + Height"

$V30
[1] "Edible ~ CapSurface + CapColor + Odor + Height"

$V31
[1] "Edible ~ CapShape + CapSurface + CapColor + Odor + Height"

我正在尝试通过 randomForest() 命令循环公式向量中的每个模型,因此我可以生成 31 个不同的随机森林模型,到目前为止我尝试创建的循环是:

for (i in 1:length(formulas)){
current_model = randomForest(formula = formulas[i], data = mushrooms)
}

但是,这一直返回错误:

Error in nrow(x) : argument "x" is missing, with no default

数据“蘑菇”包含公式中的变量作为列标题的一部分,我想知道我可以做些什么来让 randomForest() 函数识别公式中的模型?例如,有没有一种方法可以将这个向量向量转换为单个向量,这样行吗?

【问题讨论】:

    标签: r for-loop vector random-forest


    【解决方案1】:

    formulas 中的 list 元素是字符串。我们可以将它们转换为formula 类,它应该可以工作。 current_model 应该是一个 list 对象,用于存储模型元素,而不是在每次迭代中仅由同一对象重新更新。如果要在 OP 的代码中工作,则“current_model”仅返回最后一个模型

    current_model <- vector('list', length(formulas))
    for(i in seq_along(formulas)) {
     current_model[[i]] <-  randomForest(formula = as.formula(formulas[i]),
              data = mushrooms)
    
     }
    

    【讨论】:

    • 非常感谢阿克伦!这非常有效!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 2012-03-11
    • 1970-01-01
    • 2020-11-14
    • 2018-06-04
    • 1970-01-01
    • 2019-11-05
    相关资源
    最近更新 更多