KNN error: could not find function "train"

Hi everybody!
this is my KNN code:

library(class)
library(ggplot2)
library(gmodels)
library(scales)
library(caret)
library(tidyverse)


db_data <- iris
row_train <- sample(nrow(iris), nrow(iris)*0.8)
db_train <- iris[row_train,]
db_test <- iris[-row_train,]

unique(db_train$Species)
table(db_train$Species)
#--------

#FIST METHOD 

#KNN
#-------
model_knn<-train(Species ~ ., data = db_train, method = "knn",tuneLength = 10)
#summary(model_knn)

set.seed(1)
model_knn<-train(Species ~ ., data = db_train, method = "knn",tuneGrid = data.frame(k = c(2:20)))
summary(model_knn)
#-------

#PREDICTION NEW RECORD
#-------
test_data <- db_test
db_test$predict <- predict(model_knn, newdata=test_data, interval='confidence')
confusionMatrix(data=factor(db_test$predict),reference=factor(db_test$Species))

but when I run model_knn I have this error:

Error in train(Species ~ ., data = db_train, method = "knn", tuneLength = 10) : 
  could not find function "train"

How can I fix it?

Hello, this seems related to an issue you reported 5 days ago.
At the time I asked you for the results of

getAnywhere(train)

you reported that restarting your session clean resolved your issue.

Perhaps try getAnywhere, oh and also you could share

sessionInfo()

which would show your loaded packages and their versions.

I know, but now I've another type of error and even if I restart R I still get this error. This is the result of getAnywhere(train)

> getAnywhere(train)
A single object matching ‘train’ was found
It was found in the following places
  namespace:generics
with value

function (x, ...) 
{
    UseMethod("train")
}
<bytecode: 0x000002573e953960>
<environment: namespace:generics>

and this is sessionInfo()

> sessionInfo()
R version 4.1.1 (2021-08-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19042)

Matrix products: default

locale:
[1] LC_COLLATE=Italian_Italy.1252  LC_CTYPE=Italian_Italy.1252    LC_MONETARY=Italian_Italy.1252
[4] LC_NUMERIC=C                   LC_TIME=Italian_Italy.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] compiler_4.1.1 generics_0.1.0 tools_4.1.1   

The information from your sessionInfo implies that caret didn't load.
did you execute library(caret) and if you did, was there an error message?

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.