title: Error in model.frame.default(form = classvariable ~ ., data = trainingDataset, : variable lengths differ (found for 'Sepal.Length')
body: <p>I've tried to look at similar questions but can't figure out my problem.</p>
  
  <p>I was already able to complete my analysis with random forest (using caret), tuning parameters separately. Now I'm trying to create a function that will perform my analysis all at once.</p>
  
  <p>I created a function with two inputs, the dataset, and variable to be classified.
  For now I'm using the iris dataset for simplicity.</p>
  
  <pre><code>RF &lt;- function(data, classvariable) {
  
                 # Best mtry
                 trControl &lt;- trainControl(method = "cv", number = 10,           
                                           search = "grid")
                 set.seed(1234)
                 tuneGrid &lt;- expand.grid(.mtry = c(1: 3))
                 RF_mtry &lt;- train(classvariable ~.,
                                  data = dataset,
                                  method = "rf",
                                  metric = "Accuracy",
                                  tuneGrid = tuneGrid,
                                  trControl = trControl,
                                  importance = TRUE,
                                  ntree = 100)
                    print(RF_mtry)
  
                 mtry = 0
                 for (i in 1:nrow(RF_mtry$results)) {
                      if (RF_mtry$results[i,2] &gt; mtry) mtry &lt;-                    
                                                       RF_mtry$results[i,2]
                 }
                 trial_mtry &lt;- c(1:3)
                 best_mtry &lt;- trial_mtry[i]
                 best_mtry
  } 
  </code></pre>
  
  <p>Once I run the function</p>
  
  <pre><code> RF(data = iris, classvariable = Species) 
  </code></pre>
  
  <p>I get the error</p>
  
  <pre><code> Error in `[.data.frame`(data, , all.vars(Terms), drop = FALSE) : 
    undefined columns selected 
  </code></pre>
  
  <p>Tried running the code without putting it in a function, so i wrote directly iris instead of dataset and Species instead of classvariable, and it works.</p>
  
  <p>previously I was getting the error</p>
  
  <pre><code>Error in model.frame.default(form = classvariable ~ ., data = trainingDataset,  : 
    variable lengths differ (found for 'Sepal.Length')  
  </code></pre>
  
  <p>Anybody have an idea why it does not work?
  Thank you very much. </p>