0
trainer <- function(training, testing){    
  trControl <- trainControl(method="cv", number=5)
  modelFit <- train(training$classe ~ ., method="rf", preProcess="pca", 
                    trControl=trControl, data=training)
  confMatrix <- confusionMatrix(testing$classe, predict(modelFit,testing))

  output <- list(modelFit, confMatrix)
  return(output)
}

The returned value is supposed to be a model, modelFit, which isn't a list, But when I check class(output[1]), it reports as a list. Seems somehow the model file is converted to a list. How to retain the original data type without converting it a list, because I need to access the model file in the return.

jbaums
  • 27,115
  • 5
  • 79
  • 119
user697911
  • 10,043
  • 25
  • 95
  • 169
  • 1
    Try `class(output[[1]])` (see [this post](http://stackoverflow.com/q/1169456/489704)) – jbaums Jun 13 '14 at 23:07
  • 2
    use double brackets: `class(output[[1]])` – Ricardo Saporta Jun 13 '14 at 23:07
  • Also note that you don't need the assignment and `return` statements. Like in Lisp, the last sub-expression in a complex expression is the value of the complex expression, so if your last line is `list(modelFit, confMatrix)` , then that list will indeed be the return value. In fact, `return` isn't viewed as good style. – Livius Jun 14 '14 at 09:57
  • The assignment and `return` have a slight overhead, too. – jbaums Jun 15 '14 at 13:30

1 Answers1

0

As indicated above, when output is a list and you use [ ] to extract elements, you will always get a list back (with the element or elements for the index you specified). However, when you use [[ ]] you will extract the element at a particular position and that element may have a different class.

You could do sapply(output, class) to see the classes of all the items in a given list.

So your function seems to be working fine, just make sure you use output<-trainer(...); output[[1]] to extract your model.

MrFlick
  • 195,160
  • 17
  • 277
  • 295