1

In the example here there is an example of how to select rows with a checkbox: R Shiny, how to make datatable react to checkboxes in datatable

That works fine. But I need to only be able to select a single row.


I got close but there are two problems:

  1. when a box is ticked the reactive is trigger twice. I don't understand why. But then again I don't understand what activates the reactive since I don't see the input directly inside the reactive...
  2. If I click on the same box twice the selection is not really updated.


Any clue appreciated.

What I got so far. I also have a feeling I am over complicating things.

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, value, ...) {
      if (length(value) == 1) value <- rep(value, len)
      inputs = character(len)
      for (i in seq_len(len)) {
        inputs[i] = as.character(FUN(paste0(id, i), label = NULL, value = value[i]))
      }
      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)) FALSE else value
      }))
    }

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

    df_old <- df


    loopData = reactive({


      checked <- shinyValue('cb_', n)

      changed <- which((checked-df_old$YN)!=0)

      print(checked)
      print(changed)

      if(length(changed)==0){ df 
        }else{


      df$cb <<- shinyInput(checkboxInput, n, 'cb_', value = rep(FALSE, n), width='1px')
      df$YN <<- FALSE

      df$YN[changed] <<- checked[changed]
      df$cb[changed] <<- shinyInput(checkboxInput, length(changed), 'cb_', value = df$YN[changed], width='1px')


      df_old <<- df
      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(), resetPaging = FALSE)
    })

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



EDIT: I adapted @Stéphane Laurent's solution to my use, but there is a slight vertical alignment issue.
enter image description here

Jan Stanstrup
  • 1,152
  • 11
  • 28

1 Answers1

1

But I need to only be able to select a single row.

In this case I would not use checkboxes, but radio buttons instead.

Is it OK like this:

library(shiny)
library(DT)

n <- 6
dat <- data.frame(
  Select = sprintf(
    '<input type="radio" name="rdbtn" value="%s"/>', 1:n
  ),
  YN = rep(FALSE, n),
  ID = 1:n,
  stringsAsFactors = FALSE
)

callback <- c(
  "$('input[name=rdbtn]').on('click', function(){",
  "  var value = $('input[name=rdbtn]:checked').val();",
  "  Shiny.setInputValue('rdbtn', value);",
  "});"
)

shinyApp(
  ui = fluidPage(
    title = "Radio buttons in a table",
    DTOutput("foo"),
    h3("Selected row:"),
    verbatimTextOutput("sel")
  ),
  server = function(input, output, session) {
    output[["foo"]] <- renderDT(
      dat, escape = FALSE, selection = 'none', server = FALSE,
      options = list(dom = 't', paging = FALSE, ordering = FALSE),
      callback = JS(callback)
    )
    output[["sel"]] <- renderPrint({
      input[["rdbtn"]]
    })
  }
)

EDIT

Here is a possibility using checkboxes with the Select extension:

library(shiny)
library(DT)

dat <- iris[1:6,]

callback <- c(
  "table.on('select', function(e, dt, type, indexes){",
  "  if(type === 'row'){",
  "    Shiny.setInputValue('selectedRow', indexes);",
  "  }",
  "});"
)

ui <- fluidPage(
  br(),
  DTOutput("tbl"),
  br(),
  h3("Selected row:"),
  verbatimTextOutput("selectedRow")
)

server <- function(input, output, session){

  output[["tbl"]] <- renderDT({
    datatable(dat, extensions = "Select", callback = JS(callback), 
              options = list(
                columnDefs = list(
                  list(targets = 0, orderable = FALSE, className = "select-checkbox")
                ),
                select = list(
                  style = "single", selector = "td:first-child"
                )
              )
    )
  })

  output[["selectedRow"]] <- renderPrint({
    input[["selectedRow"]] + 1
  })

}

shinyApp(ui, server)
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
  • Thanks. Almost usable for me. But I would need to also be able to leave everything "unchecked" and "unselect" if I had selected by mistake. My use case is curating some data manually and I need to be able to select the "right" option. But there might not be a correct one. Hence I should also be able to have no selection. – Jan Stanstrup Feb 25 '20 at 14:56
  • @JanStanstrup Please see my edit. This one allows to deselect the selected row. – Stéphane Laurent Feb 25 '20 at 15:32
  • Absolutely awesome! Thanks so much! – Jan Stanstrup Feb 25 '20 at 15:35
  • Any idea if I can vertically align the boxes? I tried with vertical-align and text-align but I could not affect the box. I was only able to affect the content which I is already aligned. – Jan Stanstrup Feb 26 '20 at 13:36
  • 1
    @JanStanstrup Try this CSS: `"table.dataTable tbody td.select-checkbox:after {top: 50% !important} table.dataTable tbody td.select-checkbox:before {top: 50% !important}"`. – Stéphane Laurent Feb 26 '20 at 14:15
  • Thanks. The CSS works. I ran into something else though. I can de-selected a row but input[["selectedRow"]] doesn't seem to update. – Jan Stanstrup Feb 26 '20 at 15:47
  • I figured it out. The following callback does it: " table.on('select', function(e, dt, type, indexes){ if(type === 'row'){ Shiny.setInputValue('selectedRow', indexes); } }); table.on('deselect', function(e, dt, type, indexes){ if(type === 'row'){ Shiny.setInputValue('selectedRow', null); } }); " – Jan Stanstrup Feb 26 '20 at 16:12
  • @JanStanstrup Ah yes I forgot that, sorry. – Stéphane Laurent Feb 26 '20 at 16:20
  • Sorry for piling on. But is there also a way to "manually" update the section on an observe? The equivalent of putting "table.rows([10]).select();" in the callback. I could re-render the table but I imagine there is a more elegant way. – Jan Stanstrup Feb 26 '20 at 18:41
  • @JanStanstrup I would do that with `Shiny.addCustomEventHandler` in the callback, and `session$sendCustomMessage` in the observer. – Stéphane Laurent Feb 26 '20 at 18:45
  • Fabulous! I had tried to do that but tried to insert it in the `"tags$script"` like in the documentation. But adding `"Shiny.addCustomMessageHandler('set_row_select', function(row) { table.rows([row]).select(); });"` to the callback worked. Then the observe just needs `session$sendCustomMessage("set_row_select", row-1)` where `row` is what you want to set. – Jan Stanstrup Feb 26 '20 at 19:11