rshinyk-meansimputets

Unable to append cluster membership from kmeans to the raw data in Shiny


I am trying to do a small shiny Kmeans exercise where i download a csv file and run kmeans on it (ignoring any required preprocessing steps)---After getting the cluster, i want to append these cluster numbers to the original data and output this in an interactive datatable(from DT package)......But i am running into an error....code below....

library(shiny)

 # Loading the required packages


pacman::p_load(Amelia,broom,caret,cluster,clustertend,clValid,corrplot,dbscan,dplyr,DT,data.table,forecast,fpc,FPDclustering,fpp,GGally,ggfortify,ggraph,ggplot2,ggrepel,ggthemes,gmodels,googleVis,gridExtra,igraph,knitr,mice,missForest,NbClust,optCluster,pacman,plyr,purrr,qcc,randomForest,rCharts,reshape2,tibble,tidyr,tidyverse,TSA,tseries,vegan,VIM,zoo) # add 'caret',`IIPR`,'ggthemes','ggraph',igraph,VIM,missForest to the list when using the script in spark envir
#compareGroups

library(markdown)
library(imputeTS)

# Define UI for application 
ui <- navbarPage(

  # Application title
  titlePanel("ShinyApp "),

  # Sidebar layout with input and output definitions ----
  sidebarLayout(

    # Sidebar panel for inputs ----
    sidebarPanel(

      # Input: Select a file ----
      fileInput("dataset", "Choose CSV File",
                multiple = TRUE,
                accept = c("text/csv",
                           "text/comma-separated-values,text/plain",
                           ".csv")),
      # Include clarifying text ----
      helpText("Note: First select the dataset of csv format only for the App to give any insight!!"),
      # Horizontal line ----
      tags$hr(),

      # Input: Checkbox if file has header ----
      checkboxInput("header", "Header", TRUE),

      # Input: Select separator ----
      radioButtons("sep", "Separator",
                   choices = c(Comma = ",",
                               Semicolon = ";",
                               Tab = "\t"),
                   selected = ","),

      # Horizontal line ----
      tags$hr(),


      # Input: actionButton() to defer the rendering of output ----
      # until the user explicitly clicks the button (rather than
      # doing it immediately when inputs change). This is useful if
      # the computations required to render output are inordinately
      # time-consuming.
      actionButton("update", "Update button", class = "btn-primary"),
      tags$hr()
      ),

      mainPanel(
        tabsetPanel(
          navbarMenu("Kmeans",
                     tabPanel("Raw data with cluster membership",
                              # Output: Interactive DT table ----
                              h4("Cluster Table"),
                              DT::dataTableOutput("cluster_table")
                     )
          ),
          tabPanel("Random Forest", "This panel is intentionally left blank")
         )
   )
)

)

# Define server logic 
server <- function(input, output) {

  datasetInput <- eventReactive(input$update, {
    read.csv(input$dataset$datapath,
             header = input$header,
             sep = input$sep)
  }, ignoreNULL = FALSE)

  #Selecting only numeric variables
  MS.num<- reactive({sapply(datasetInput(), is.numeric)})
  MS.DATA.IN.NUM <- reactive({datasetInput()[ , MS.num()]})
  # imputing NAs by zeros
  df<- reactive({imputeTS::na.replace(MS.DATA.IN.NUM(), 0)})
  # Keeping a sample of 10k for modeling
  sample_data <-reactive({df()[1:10000,]})

  #### Kmeans

  opt.cluster=9
  set.seed(115)
  MS.DATA.KMEANS.Mdl <- reactive({kmeans(scale(sample_data()),opt.cluster,nstart=25)})

  # appending clusters to the raw sample data
  MS.DATA_KMEANS<-reactive({
    x<-MS.DATA.KMEANS.Mdl()$cluster
    sample_data()$cluster.kmeans <-x 
  })

  output$cluster_table <- renderDataTable({
    DT::datatable(MS.DATA_KMEANS())
  })   
}

# Run the application 
shinyApp(ui = ui, server = server)

I am getting the following error:

Error in <-: invalid (NULL) left side of assignment
Stack trace (innermost first):
    96: <reactive:MS.DATA_KMEANS> [C:\Users\ADMIN\Documents\shiny_test/app.R#124]
    85: MS.DATA_KMEANS
    84: base::rownames
    83: DT::datatable
    82: exprFunc [C:\Users\ADMIN\Documents\shiny_test/app.R#128]
    81: widgetFunc
    80: func
    79: origRenderFunc
    78: renderFunc
    77: origRenderFunc
    76: output$cluster_table
     1: runApp

Dont know what i am doing wrong??


Solution

  • Found the solution...

    appending clusters to the raw sample data

    x<-reactive({
        cluster<-MS.DATA.KMEANS.Mdl()$cluster
        cluster
      })
    
      output$x1 <- renderPrint({
        dataset <- x()
        table(dataset)
      })
    
      add_to_df <- reactive({
        sample_data1<-cbind(sample_data(),x())
        sample_data1
    
      })
    
      output$cluster_table <- renderDataTable({
        DT::datatable(add_to_df())
      })
    

    Just had to use cbind() here....