简体   繁体   中英

I'm working with R. I am performing a k-NN analysis on the training data, but I keep getting an error on my knn function. How can I fix this

Here's my input:

For (j in I: m ){
      model.knn <- knn(train.set[,vars],
                             test.set[,vars],
                             cl = class.train,
                             k=j,
                             prob = T)
       error <- table(model.knn, class.test)

       knn.error[j] <- (error[1,2] + 
                              error [2,1]/sum(error))
}

Output:

Error in [.data.frame'(train.set, , vars) : undefined columns selected 

Based on the error you are getting, it seems that you are trying to subset data frame train.set by selecting columns which do not exist in that data frame. To rectify this, try the following code:

> colnames(train.set)    # lists all column names in train.set
> vars                   # prints all columns you are trying to select

You need to make certain that train.set has the columns which vars is trying to reference. And while you are at it, you should do a similar check for the test.set data frame.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM