使用变量在 R 中的预测函数中定义训练列

Using a variable for defining the training column in the predict function in R

假设我们有以下代码(此问题的 training/testing 分区无关)。

library(caret)
data(iris)
train( Species ~ .,data=iris, method="rf" )  

现在运行正常。我想要做的是提供我试图使用变量预测的列(因为我要从 GUI 中获取它)。让我们使用下面的示例代码:

library(caret)
data(iris)
colName <- 'Species'
train( colName ~ .,data=iris, method="rf" )  

这不起作用,因为 colName 不是数据集中的列之一。那么有没有办法做到这一点?我到处搜索,一无所获。有人请帮助我:(。

这是一个足够简单的案例,所以按以下方式使用 paste 应该没问题:

library(caret)
data(iris)
colName <- 'Species'

#create the formula using as.formula and paste
formula <- as.formula(paste(colName, ' ~ .' ))

#run model
train(formula, data=iris, method="rf" )  

输出:

> train( formula,data=iris, method="rf" )
Random Forest 

150 samples
  4 predictor
  3 classes: 'setosa', 'versicolor', 'virginica' 

No pre-processing
Resampling: Bootstrapped (25 reps) 

Summary of sample sizes: 150, 150, 150, 150, 150, 150, ... 

Resampling results across tuning parameters:

  mtry  Accuracy   Kappa      Accuracy SD  Kappa SD  
  2     0.9481249  0.9216819  0.02790700   0.04200793
  3     0.9473557  0.9205465  0.02893104   0.04347956
  4     0.9466284  0.9194525  0.02920803   0.04388548

Accuracy was used to select the optimal model using  the largest value.
The final value used for the model was mtry = 2.