Reputation: 1
I am trying to use naiveBayes to fit and classify a data with binary (location=3 or not) outcome and assess its performance on test data by resampling.
I got an error code: Error in table(train$prog, trainPred) : all arguments must have the same length
Here is my reproducible code:
wifiDat <- read.table("wifi_localization.txt",sep="\t")
colnames(wifiDat)
dim(wifiDat)
summary(wifiDat)
head(wifiDat)
colnames(wifiDat) <- c("WF1", "WF2", "WF3", "WF4", "WF5", "WF6", "WF7", "RM")
wifiDat$RM <- factor(wifiDat$RM)
library(e1071)
wifiDat$RM <- factor(wifiDat$RM)
set.seed(1)
row.number = sample(1:nrow(wifiDat), 0.25*nrow(wifiDat))
train = wifiDat[row.number,]
test = wifiDat[-row.number,]
NBclassfier=naiveBayes(RM~WF1+WF2+WF3+WF4+WF5+WF6+WF7, data=train)
print(NBclassfier)
printALL=function(model){
trainPred=predict(model, newdata = train, type = "class")
trainTable=table(train$prog, trainPred)
testPred=predict(NBclassfier, newdata=test, type="class")
testTable=table(test$prog, testPred)
trainAcc=(trainTable[1,1]+trainTable[2,2]+trainTable[3,3])/sum(trainTable)
testAcc=(testTable[1,1]+testTable[2,2]+testTable[3,3])/sum(testTable)
message("Contingency Table for Training Data")
print(trainTable)
message("Contingency Table for Test Data")
print(testTable)
message("Accuracy")
print(round(cbind(trainAccuracy=trainAcc, testAccuracy=testAcc),3))
}
printALL(NBclassfier)
Here is my sample data
V1. V2. V3. V4. V5. V6. V7. V8
-64 -56 -61 -66 -71 -82 -81 1
-68 -57 -61 -65 -71 -85 -85 2
-63 -60 -60 -67 -76 -85 -84 3
-61 -60 -68 -62 -77 -90 -80 4
-63 -65 -60 -63 -77 -81 -87 1
-64 -55 -63 -66 -76 -88 -83 1
-65 -61 -65 -67 -69 -87 -84 2
-61 -63 -58 -66 -74 -87 -82 3
-65 -60 -59 -63 -76 -86 -82 4
-62 -60 -66 -68 -80 -86 -91 1
-67 -61 -62 -67 -77 -83 -91 1
-65 -59 -61 -67 -72 -86 -81 1
-63 -57 -61 -65 -73 -84 -84 1
Please how can I fix the error?
Upvotes: 0
Views: 2020
Reputation: 1291
If you look at the traceback of your error, you should see that the issue lies in the table(train$prog, trainPred)
part of your function. The base::table()
function requires you to provide objects of the same length for the ...
argument, as
Stepping through your custom function, you'll see that the length of trainPred
is 3, and train$prog
doesn't exist (and all columns of train
are of length 10 anyway). Hence the error.
Are you missing a step somewhere?
Upvotes: 1