####We need to read data from internet from the following URL
Heart<-read.csv("http://www-bcf.usc.edu/~gareth/ISL/Heart.csv")
#View(Heart)
#head(Heart)
Heart<-Heart[,-1]
library(caret)
## Loading required package: lattice
## Loading required package: ggplot2
library(tree)
split<-createDataPartition(y=Heart$AHD,p=.7,list=F)
train<-Heart[split,]
test<-Heart[-split,]
trees<-tree(AHD~.,train)
plot(trees)
text(trees)

cv.trees<-cv.tree(trees,FUN = prune.misclass)
plot(cv.trees)

prune.trees<-prune.misclass(trees,best = 4)
plot(prune.trees)
text(prune.trees)

tree.pred<-predict(prune.trees,test,type='class')
confusionMatrix(tree.pred,test$AHD)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction No Yes
##        No  44  13
##        Yes  5  28
##                                           
##                Accuracy : 0.8             
##                  95% CI : (0.7025, 0.8769)
##     No Information Rate : 0.5444          
##     P-Value [Acc > NIR] : 3.697e-07       
##                                           
##                   Kappa : 0.5903          
##  Mcnemar's Test P-Value : 0.09896         
##                                           
##             Sensitivity : 0.8980          
##             Specificity : 0.6829          
##          Pos Pred Value : 0.7719          
##          Neg Pred Value : 0.8485          
##              Prevalence : 0.5444          
##          Detection Rate : 0.4889          
##    Detection Prevalence : 0.6333          
##       Balanced Accuracy : 0.7904          
##                                           
##        'Positive' Class : No              
##