Search code examples
rshinydt

How to pass datatables row to machine learning model by clicking button?


I am creating a shiny machine learning application. I am displaying data in datatables and want to pass the data to machine learning model by selecting the row and clicking the button to get result. How can it be done in shiny?


Solution

  • I think I understand what you are trying to do. Hope this minimal example I made will help you. Use DT for table rendering and row selection (here i suppressed the selection of more than one row because I deduced that is what you want). Use button and isolate to run model only if row is selected and button is pressed. I didn't fit a model here, instead I made a plot with highlited row data, but the principle is exactly the same.

    library(shiny)
    library(DT)
    
    server <- function(input, output, session) {
    
      output$x1 = DT::renderDataTable(mtcars, server = FALSE, selection = "single")
    
      # client-side processing
      output$x2 = renderPrint({
        s = input$x1_rows_selected
        if (length(s)) {
          cat('These rows were selected:\n\n')
          cat(s, sep = ', ')
        }
      })
    
    
      # highlight selected rows in the scatterplot - here you add your model
      output$x3 = renderPlot({
        input$run_model                                 # button input
        s = isolate(input$x1_rows_selected)             # use isolate to run model only on button press
        par(mar = c(4, 4, 1, .1))
        plot(mtcars[, 2:3])
          if (length(s)) points(mtcars[s, 2:3, drop = FALSE], pch = 19, cex = 2) 
      })
    
    }
    
    ui <- fluidPage(
    
      title = 'Select Table Rows',
    
      h1('A Client-side Table'),
    
      fluidRow(
        column(9, DT::dataTableOutput('x1')),
        column(3, verbatimTextOutput('x2'))
      ),
    
      hr(),
    
      h1('Model'),
    
      fluidRow(
        column(6, actionButton("run_model", "Go")),
        column(9, plotOutput('x3', height = 500))
    
      )
    
    )
    
    shinyApp(ui = ui, server = server)