Calculating prediction accuracy of a tree using rpart's predict method
<p>I have constructed a decision tree using rpart for a dataset. </p>

<p>I have then divided the data into 2 parts - a training dataset and a test dataset. A tree has been constructed for the dataset using the training data. I want to calculate the accuracy of the predictions based on the model that was created.</p>

<p>My code is shown below:</p>

<pre><code>library(rpart)
#reading the data
data = read.table("source")
names(data) &lt;- c("a", "b", "c", "d", "class")

#generating test and train data - Data selected randomly with a 80/20 split
trainIndex  &lt;- sample(1:nrow(x), 0.8 * nrow(x))
train &lt;- data[trainIndex,]
test &lt;- data[-trainIndex,]

#tree construction based on information gain
tree = rpart(class ~ a + b + c + d, data = train, method = 'class', parms = list(split = "information"))
</code></pre>

<p>I now want to calculate the accuracy of the predictions generated by the model by comparing the results with the actual values train and test data however I am facing an error while doing so.</p>

<p>My code is shown below:</p>

<pre><code>t_pred = predict(tree,test,type="class")
t = test['class']
accuracy = sum(t_pred == t)/length(t)
print(accuracy)
</code></pre>

<p>I get an error message that states - </p>

<blockquote>
  <p>Error in t_pred == t : comparison of these types is not implemented In
  addition: Warning message: Incompatible methods ("Ops.factor",
  "Ops.data.frame") for "=="</p>
</blockquote>

<p>On checking the type of t_pred, I found out that it is of type integer however the documentation</p>

<p>(<a href="https://stat.ethz.ch/R-manual/R-devel/library/rpart/html/predict.rpart.html" rel="nofollow noreferrer">https://stat.ethz.ch/R-manual/R-devel/library/rpart/html/predict.rpart.html</a>)</p>

<p>states that the <code>predict()</code> method must return a vector. </p>

<p>I am unable to understand why is the type of the variable is an integer and not a list. Where have I made the mistake and how can I fix it?</p>