1

I am Knitting the result from the R Markdown file into a PDF/HTML/Word. The statistics result displaying in R is different after it is output into a PDF/HTML/Word. The results in the 3 format are the same: 0.75. It is different from the result in R: 0.64.

The code was in an R Notebook. The Knit output was wrong. So I copied and pasted the code into an R Markdown file.

I tried Knit into HTML, WORD and PDF format, the code as followed.

library(caret)
library(AppliedPredictiveModeling)
set.seed(3433)
data(AlzheimerDisease)
adData <- data.frame(diagnosis, predictors)
inTrain <- createDataPartition(adData$diagnosis, p=3/4)[[1]]
train <- adData[inTrain,]
test <- adData[-inTrain,]
IL<-grep("^[Ii][Ll].*", names(train))

newtrain<-train[,c(names(train)[IL], "diagnosis")]
newtest<-test[,c(names(test)[IL], "diagnosis")]

nonPCA<-train(diagnosis~., data = newtrain, method = "glm")
nonpcaresult<-confusionMatrix(newtest[,13], predict(nonPCA, newtest[,-13]))
nonpcaresult

pca_obj<-preProcess(newtrain[,-13], method=c('center','scale','pca'), thresh = 0.8)
pca_train_pred<-predict(pca_obj, newtrain[,-13])
pca_test_pred<-predict(pca_obj, newtest[,-13])
train2<-data.frame(newtrain[,13],pca_train_pred)
names(train2)[1]<-"diagnosis"
yespac<-train(diagnosis~., data = train2, method="glm")
yespacreslt<-confusionMatrix(newtest$diagnosis, predict(yespac, pca_test_pred))
yespacreslt

The accuracy should be 0.64 and 0.71, which is in the R Console. The output into HTML/PDF/Word should be the same. Now I am getting 0.75 and 0.71, which is wrong.

  • Hi, have you tried a fresh restart of R, Rmarkdown is like an enviroment without access to anything else, so mimic that on your enviroment – Bruno Aug 24 '19 at 18:08
  • Welcome to SO! With your seed I'm getting 0.7561 and 0.7195 accuracy without RMarkdown. Likely Bruno's comment is correct. Restart R and clear your working environment and rerun the code. – Daniel Winkler Aug 24 '19 at 18:58
  • I agree with Bruno and Daniel. I knitted to HTML and got the same answers as Daniel. – markhogue Aug 24 '19 at 20:33
  • I finally found that it was due to rounding numbers in the console and not knitted documents as explained here: https://stackoverflow.com/questions/56268011/sample-function-gives-different-result-in-console-and-in-knitted-document-when-s – ForEverNewbie Nov 16 '20 at 01:08

0 Answers0