#install.packages("randomForest")
library(randomForest)
## randomForest 4.6-12
## Type rfNews() to see new features/changes/bug fixes.
library(ISLR)
#View(as.data.frame(Smarket))
table(Smarket$Year)
## 
## 2001 2002 2003 2004 2005 
##  242  252  252  252  252
train<-Smarket[Smarket$Year<2004,]
test<-Smarket[Smarket$Year>=2004,]
fit<-randomForest(Direction~Lag1+Lag2+Lag3,data=train,
                  ntree=100,importance=T)
test.pred<-predict(fit,test,type='class')
table(test.pred,test$Direction)
##          
## test.pred Down  Up
##      Down  111 134
##      Up    112 147
library(caret)
## Loading required package: lattice
## Loading required package: ggplot2
## 
## Attaching package: 'ggplot2'
## The following object is masked from 'package:randomForest':
## 
##     margin
confusionMatrix(test$Direction,test.pred)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Down  Up
##       Down  111 112
##       Up    134 147
##                                           
##                Accuracy : 0.5119          
##                  95% CI : (0.4673, 0.5564)
##     No Information Rate : 0.5139          
##     P-Value [Acc > NIR] : 0.5533          
##                                           
##                   Kappa : 0.0207          
##  Mcnemar's Test P-Value : 0.1806          
##                                           
##             Sensitivity : 0.4531          
##             Specificity : 0.5676          
##          Pos Pred Value : 0.4978          
##          Neg Pred Value : 0.5231          
##              Prevalence : 0.4861          
##          Detection Rate : 0.2202          
##    Detection Prevalence : 0.4425          
##       Balanced Accuracy : 0.5103          
##                                           
##        'Positive' Class : Down            
##