dimanche 18 février 2018

R Shiny, how to make datatable react to checkboxes in datatable

I would like my datatable to display content which depends on the status of checkboxes contained in the table. I have found help with both, including checkboxes in a DT as well as changing data table content, but when I try and combine these solutions I don't get what I want. When checking a box, the table is redrawn twice, the first time the way I want but a moment later it switches back.

This is the code which should almost do... Is there someone out there to help before I get crazy?

library(shiny)
library(DT)
shinyApp(
  ui = fluidPage(
    DT::dataTableOutput('x1'),
    verbatimTextOutput('x2')
  ),

  server = function(input, output, session) {
    # create a character vector of shiny inputs
    shinyInput = function(FUN, len, id, ...) {
      inputs = character(len)
      for (i in seq_len(len)) {
        inputs[i] = as.character(FUN(paste0(id, i), label = NULL, ...))
      }
      inputs
    }

    # obtain the values of inputs
    shinyValue = function(id, len) {
      unlist(lapply(seq_len(len), function(i) {
        value = input[[paste0(id, i)]]
        if (is.null(value)) TRUE else value
      }))
    }

    n = 6
    df = data.frame(
      cb = shinyInput(checkboxInput, n, 'cb_', value = TRUE, width='1px'),
      month = month.abb[1:n],
      YN = rep(TRUE, n),
      ID = seq_len(n),
      stringsAsFactors = FALSE)

    loopData = reactive({
      df$YN <<- shinyValue('cb_', n)
      df
    })

    output$x1 = DT::renderDataTable(
      isolate(loopData()),
      escape = FALSE, selection = 'none',
      options = list(
        dom = 't', paging = FALSE, ordering = FALSE,
        preDrawCallback = JS('function() {    Shiny.unbindAll(this.api().table().node()); }'),
        drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')#,
      ))

    proxy = dataTableProxy('x1')

    observe({
      replaceData(proxy, loopData())
    })

    output$x2 = renderPrint({
      data.frame(Like = shinyValue('cb_', n))
    })
  }
)




Aucun commentaire:

Enregistrer un commentaire