我正在尝试创建一个动态的机器学习应用,允许用户上传数据集,并使用随机森林模型预测数据集的第一列。
我在使用randomforest()
函数时遇到了问题,特别是当我尝试将响应变量指定为数据集的第一列时。以下面的例子为例,我使用了iris数据集,并将响应变量Species移动到第一列的位置。
这是我的尝试:
model <- randomForest(names(DATA[1]) ~ ., data = DATA, ntree = 500, mtry = 3, importance = TRUE)
然而,这不起作用。我得到的错误是:
错误:变量长度不同(发现于’Species’)
只有当我手动指定响应变量时,应用和函数才似乎能正常工作,像这样:
model <- randomForest(Species ~ ., data = DATA, ntree = 500, mtry = 3, importance = TRUE)
我尝试使用paste()
函数来解决这个问题,但没有成功。
我应该如何编写代码才能让它正常工作呢?
回答:
看起来你想从字符串中构建一个公式。你可以使用eval
和parse
来实现。像这样应该可以工作:
model <- randomForest(eval(parse(text = paste(names(DATA)[1], "~ ."))), data = DATA, ntree = 500, mtry = 3, importance = TRUE)
使用原始iris数据集的例子:
model <- randomForest(eval(parse(text = paste(names(iris)[5], "~ ."))), data = iris, ntree = 500, mtry = 3, importance = TRUE)modelCall: randomForest(formula = eval(parse(text = paste(names(iris)[5], "~ ."))), data = iris, ntree = 500, mtry = 3, importance = TRUE) Type of random forest: classification Number of trees: 500No. of variables tried at each split: 3 OOB estimate of error rate: 4%Confusion matrix: setosa versicolor virginica class.errorsetosa 50 0 0 0.00versicolor 0 47 3 0.06virginica 0 3 47 0.06