Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: attempt to apply non-function when using caret package

I'm trying to understand a bit more about the caret package and ran into a roadblock that I'm unsure how to resolve.

#loading up libraries
library(MASS)
library(caret)
library(randomForest)
data(survey)
data<-survey

#create training and test set
split <- createDataPartition(data$W.Hnd, p=.8)[[1]]
train<-data[split,]
test<-data[-split,]


#creating training parameters
control <- trainControl(method = "cv",
                        number = 10, 
                        p =.8, 
                        savePredictions = TRUE, 
                        classProbs = TRUE, 
                        summaryFunction = "twoClassSummary")

#fitting and tuning model
tuningGrid <- data.frame(.mtry = floor(seq(1 , ncol(train) , length = 6)))
rf_tune <- train(W.Hnd ~ . , 
            data=train, 
            method = "rf" ,
            metric = "ROC",
            trControl = control)

keep getting an error:

Error in evalSummaryFunction(y, wts = weights, ctrl = trControl, lev = classLevels,  : 
  attempt to apply non-function

I have confirmed that my DV (W.Hnd) is a factor level so a random forest would be appropriate to use for classification. My assumption is that caret doesn't know to apply to the randomForest algorithm? Other than that I have no idea.

like image 501
Minh Mai Avatar asked Apr 28 '26 06:04

Minh Mai


1 Answers

You have quotes around "twoClassSummary", which makes this a character vector. R is trying to apply this as a function, which is causing the error.

Remove the quotes and try your script again. This should enable the function twoClassSummary to be called correctly.

#creating training parameters
control <- trainControl(method = "cv",
                        number = 10, 
                        p =.8, 
                        savePredictions = TRUE, 
                        classProbs = TRUE, 
                        summaryFunction = twoClassSummary)
like image 130
Whitebeard Avatar answered Apr 30 '26 20:04

Whitebeard