---
title: "Classification Tree Modelling"
output: html_document
runtime: shiny
---


```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
library(caret)
library(e1071)
library(rhandsontable)
library(datasets)
library(rpart)
library(rpart.plot)
library(party)

```

```{r,echo=FALSE}
options(shiny.maxRequestSize = 100 * 1024^2)
sidebarPanel(
  checkboxInput("ex","Uncheck for using your own file",value = TRUE),
  fileInput("file", "Upload the *.csv file with headers"),
 selectInput("mt","Choose Type of Tree model",choices = c("RPART","CTREE"),selected = "RPART"),
 conditionalPanel(condition = "input.mt =='RPART'",
                         checkboxInput("Prune", label = "Check forPrune",value = FALSE),
                  numericInput("PruneV", label = "Enter Prune value",value ="0",step = 0.001)
                  ),
 
  sliderInput("train_num", label = "Enter the proportion of training dataset:",
                     min = 0.6, max = 1, value = 0.6, step = 0.01),
  
  uiOutput("vx"),
  uiOutput("vy"),
  downloadButton("downloadPlot", "Download Plot") 
  
)
#
mainPanel(
   tabsetPanel(type = "tab",
                tabPanel("Model Summary", verbatimTextOutput("AD") ),
                tabPanel("Model Visualization", plotOutput("MV") ),
                tabPanel("Model Evaluation",verbatimTextOutput("ME")),
                tabPanel("Model Deployment",verbatimTextOutput("MD"))
                ),
    h6("Edit the test data record"),
   rHandsontableOutput("testdata"),
   h6("", tags$img(src ="K.JPG", height= 400, width=400))
)
output$AD<-renderPrint({
   if(input$ex == TRUE)
     {data("iris")
      data = iris}
     else{
  file1 = input$file
     if(is.null(file1)){return()}
     
     data =  read.table(file =  file1$datapath,sep =",",header = TRUE)
     if(is.null(data())){return()}
      quantdata = select_if(data,is.numeric)
      qualdata =  select_if(data,is.character)
      qualdata = data.frame(lapply(qualdata,as.factor))
      data =  data.frame(cbind(quantdata,qualdata))
     }
     ds = data
     
     ds = select(ds,input$variablex)
     mod = paste(input$variabley,"~.")
     options(scipen = 999)
       prop = input$train_num
       set.seed(1)
       dataframe =  ds
       train.rows = sample(row.names(dataframe),dim(dataframe)[1]*prop)
       dataframet = dataframe[train.rows,]
       valid.rows = setdiff(row.names(dataframe),train.rows)
       dataframev = dataframe[valid.rows,]    
 if(input$mt == "RPART")
     {
       model = rpart(formula = as.formula(mod),data = dataframet)
        if(input$Prune == "TRUE")
      {model = prune(model,cp = input$PruneV)}
      print(summary(model))
     }
  if(input$mt == "CTREE") 
  {
       model = ctree(formula = as.formula(mod),data = dataframet)
      print((model))
     }
     
     
})
output$MV<-renderPlot({ 
  if(input$ex == TRUE)
     {data("iris")
      data = iris}
     else{
  file1 = input$file
     if(is.null(file1)){return()}
     
     data =  read.table(file =  file1$datapath,sep =",",header = TRUE)
     if(is.null(data())){return()}
     quantdata = select_if(data,is.numeric)
      qualdata =  select_if(data,is.character)
      qualdata = data.frame(lapply(qualdata,as.factor))
      data =  data.frame(cbind(quantdata,qualdata))
     }
     ds = data
     
     ds = select(ds,input$variablex)
     mod = paste(input$variabley,"~.")
     options(scipen = 999)
       prop = input$train_num
       set.seed(1)
       dataframe =  ds
       train.rows = sample(row.names(dataframe),dim(dataframe)[1]*prop)
       dataframet = dataframe[train.rows,]
       valid.rows = setdiff(row.names(dataframe),train.rows)
       dataframev = dataframe[valid.rows,]   
    if(input$mt == "RPART")
   {  model = rpart(formula = as.formula(mod),data = dataframet)
      if(input$Prune == "TRUE")
      {model = prune(model,cp = input$PruneV)}
    prp(model,type = 2, extra =104, fallen.leaves = TRUE,main =  "Classification Tree using RPART Algorithm")
    }
    if(input$mt == "CTREE")
 {    model = ctree(formula = as.formula(mod),data = dataframet)
    plot(model,main =  "Classification Tree using CTREE Algorithm")
    }

     
     
})

output$ME<-renderPrint({
   if(input$ex == TRUE)
     {data("iris")
      data = iris}
     else
     {
  file1 = input$file
     if(is.null(file1)){return()}
     
     data =  read.table(file =  file1$datapath,sep =",",header = TRUE)
     if(is.null(data())){return()}
     quantdata = select_if(data,is.numeric)
      qualdata =  select_if(data,is.character)
      qualdata = data.frame(lapply(qualdata,as.factor))
      data =  data.frame(cbind(quantdata,qualdata))
     }
     ds = data
     
     ds = select(ds,input$variablex)
     mod = paste(input$variabley,"~.")
     options(scipen = 999)
       prop = input$train_num
       set.seed(1)
       dataframe =  ds
       train.rows = sample(row.names(dataframe),dim(dataframe)[1]*prop)
       dataframet = dataframe[train.rows,]
       valid.rows = setdiff(row.names(dataframe),train.rows)
       dataframev = dataframe[valid.rows,]    
 if(input$mt == "RPART")
     {  cat(sprintf("\nRPART ALGORITHM\n") ) 
       model = rpart(formula = as.formula(mod),data = dataframet)
        if(input$Prune == "TRUE")
      {model = prune(model,cp = input$PruneV)}
       if(prop <1 )
     {   cat(sprintf("\nValidation data is used\n"))
         
         prediction =  predict(model,newdata = dataframev,type = "class")
       attach(dataframev)
       }
       else
       {
         cat(sprintf("\nTraining data is used\n"))
         prediction =  predict(model,newdata =  dataframet,type = "class")
         attach(dataframet)
       }
      #print(summary(model))
     }
  if(input$mt == "CTREE") 
  {   cat(sprintf("\nCTREE ALGORITHM\n") ) 
       model = ctree(formula = as.formula(mod),data = dataframet)
     if(prop <1 )
     {   cat(sprintf("\nValidation data is used\n"))
         
         prediction =  predict(model,newdata = dataframev,type = "response")
       attach(dataframev)
       }
       else
       {
         cat(sprintf("\nTraining data is used\n"))
         prediction =  predict(model,newdata =  dataframet,type = "response")
         attach(dataframet)
       }
     }
      
       
    # print(prediction)
        
     print(confusionMatrix(as.factor(prediction),as.factor(get(input$variabley))))
#     } 
   

     
     
})

output$MD<-renderPrint({
   if(input$ex == TRUE)
     {data("iris")
      data = iris}
     else
     {
  file1 = input$file
     if(is.null(file1)){return()}
     
     data =  read.table(file =  file1$datapath,sep =",",header = TRUE)
     if(is.null(data())){return()}
     quantdata = select_if(data,is.numeric)
      qualdata =  select_if(data,is.character)
      qualdata = data.frame(lapply(qualdata,as.factor))
      data =  data.frame(cbind(quantdata,qualdata))
     }
     ds = data
     
     ds = select(ds,input$variablex)
     mod = paste(input$variabley,"~.")
     options(scipen = 999)
       prop = input$train_num
       set.seed(1)
       dataframe =  ds
       train.rows = sample(row.names(dataframe),dim(dataframe)[1]*prop)
       dataframet = dataframe[train.rows,]
       valid.rows = setdiff(row.names(dataframe),train.rows)
       dataframev = dataframe[valid.rows,]    
 if(input$mt == "RPART")
    {   cat(sprintf("\nRPART ALGORITHM\n") )
       model = rpart(formula = as.formula(mod),data = dataframet)
        if(input$Prune == "TRUE")
      {model = prune(model,cp = input$PruneV)}
       test_data = data.frame(hot_to_r(input$testdata))
       if(ncol(test_data)== 1)
       { df  = select(dataframet,-c(input$variabley))
         colnames(test_data)=  colnames(df)
       }
      prediction =  predict(model,newdata = test_data,type = "class")
     test_data$predictedvalue = prediction
       print(test_data)
   } 
   
if(input$mt == "CTREE")
    {
        cat(sprintf("\nCTREE ALGORITHM\n") )
       model = ctree(formula = as.formula(mod),data = dataframet)
       test_data = data.frame(hot_to_r(input$testdata))
       if(ncol(test_data)== 1)
       { df  = select(dataframet,-c(input$variabley))
         colnames(test_data)=  colnames(df)
       }
      prediction =  predict(model,newdata = test_data,type = "response")
     test_data$predictedvalue = prediction
       print(test_data)
   }
     
     
})

output$vx <- renderUI({
   
 if(input$ex == TRUE)
     {data("iris")
      data = iris}
     else
     {
     
     file1 = input$file
     if(is.null(file1)){return()}
     
     data =  read.table(file =  file1$datapath,sep =",",header = TRUE)
     if(is.null(data())){return()}
     quantdata = select_if(data,is.numeric)
      qualdata =  select_if(data,is.character)
      qualdata = data.frame(lapply(qualdata,as.factor))
      data =  data.frame(cbind(quantdata,qualdata))
    
     }
     
    checkboxGroupInput("variablex","Select the variables",choices = colnames(data),selected = colnames(data))
    
    
  


  })
output$vy <- renderUI({
   
 if(input$ex == TRUE)
     {data("iris")
      data = iris}
     else
     {
     
     file1 = input$file
     if(is.null(file1)){return()}
     
     data =  read.table(file =  file1$datapath,sep =",",header = TRUE)
     if(is.null(data())){return()}
     quantdata = select_if(data,is.numeric)
      qualdata =  select_if(data,is.character)
      qualdata = data.frame(lapply(qualdata,as.factor))
      data =  data.frame(cbind(quantdata,qualdata))
     }
    ds = data
    ds = select(ds,input$variablex) 
    ds = select_if(ds,is.factor)
     
    selectInput("variabley","Select the dependent variable",choices = colnames(ds),selected = "" )


  })

output$testdata <- renderRHandsontable({
   
 if(input$ex == TRUE)
     {data("iris")
      data = iris}
     else{
     
     file1 = input$file
     if(is.null(file1)){return()}
     
     data =  read.table(file =  file1$datapath,sep =",",header = TRUE)
     if(is.null(data())){return()}
     quantdata = select_if(data,is.numeric)
      qualdata =  select_if(data,is.character)
      qualdata = data.frame(lapply(qualdata,as.factor))
      data =  data.frame(cbind(quantdata,qualdata))
     }
    
    ds = data
    ds = select(ds,input$variablex) 
    
     ds = select(ds,-c(input$variabley))
    
 
   rhandsontable(data.frame(ds[1,]))
    
   

  })


output$downloadPlot<- downloadHandler(
    filename = function() {
      paste("Treeplot", ".png", sep = "")
    },
    content = function(file) {
      png(file)
if(input$ex == TRUE)
     {data("iris")
      data = iris}
     else{
  file1 = input$file
     if(is.null(file1)){return()}
     
     data =  read.table(file =  file1$datapath,sep =",",header = TRUE)
     if(is.null(data())){return()}
     quantdata = select_if(data,is.numeric)
      qualdata =  select_if(data,is.character)
      qualdata = data.frame(lapply(qualdata,as.factor))
      data =  data.frame(cbind(quantdata,qualdata))
     }
     ds = data
     
     ds = select(ds,input$variablex)
     mod = paste(input$variabley,"~.")
     options(scipen = 999)
       prop = input$train_num
       set.seed(1)
       dataframe =  ds
       train.rows = sample(row.names(dataframe),dim(dataframe)[1]*prop)
       dataframet = dataframe[train.rows,]
       valid.rows = setdiff(row.names(dataframe),train.rows)
       dataframev = dataframe[valid.rows,]   
    if(input$mt == "RPART")
   {  model = rpart(formula = as.formula(mod),data = dataframet)
      if(input$Prune == "TRUE")
      {model = prune(model,cp = input$PruneV)}
    prp(model,type = 2, extra =104, fallen.leaves = TRUE,main =  "Classification Tree using RPART Algorithm")
    }
    if(input$mt == "CTREE")
 {    model = ctree(formula = as.formula(mod),data = dataframet)
    plot(model,main =  "Classification Tree using CTREE Algorithm")
    }
      dev.off()
    })
