Adding radiobutton to select a DataTable row in Shiny

青春壹個敷衍的年華 提交于 2019-12-22 09:39:23

问题


I need to add radiButtons to select rows in Data, i.e. the radiobutton choosen should be passed to input. I cannot use built in row selection in DT. I really need to use radiobuttons to select the row. This is what is wanted:

Using https://yihui.shinyapps.io/DT-radio/ I am able to select COLUMNS. Es:

library(shiny)
library(DT)
shinyApp(
ui = fluidPage(
title = 'Radio buttons in a table',
DT::dataTableOutput('foo'),
verbatimTextOutput("test")
),
server = function(input, output, session) {
m = matrix(
  c(round(rnorm(24),1), rep(3,12)), nrow = 12, ncol = 3, byrow = F,
  dimnames = list(month.abb, LETTERS[1:3])
)
for (i in seq_len(nrow(m))) {
  m[i, 3] = sprintf(
    if_else(i == 1,
            '<input type="radio" name="%s" value="%s" checked="checked"/>',
            '<input type="radio" name="%s" value="%s"/>'),
    "C", month.abb[i]
  )
}
m=t(m)

output$foo = DT::renderDataTable(
  m, escape = FALSE, selection = 'none', server = FALSE,
  options = list(dom = 't', paging = FALSE, ordering = FALSE),
  callback = JS("table.rows().every(function() {
      var $this = $(this.node());
                $this.attr('id', this.data()[0]);
                $this.addClass('shiny-input-radiogroup');
 });
                Shiny.unbindAll(table.table().node());
                Shiny.bindAll(table.table().node());")
 )
output$test <- renderPrint(str(input$C))
}
)

The result is:

Naively, I tried to remove m=t(m) and changing rows to columns in the callback. This is not working because the callback function in the example is adding class and id to the last , which have no counterpart for column.

Any idea?


回答1:


A "dirty" fix could be to wrap the whole datatable in a div with the C id and the shiny-input-radiogroup class:

shinyApp(
  ui = fluidPage(
    title = 'Radio buttons in a table',
    tags$div(id="C",class='shiny-input-radiogroup',DT::dataTableOutput('foo')),
    verbatimTextOutput("test")
  ),
  server = function(input, output, session) {
    m = matrix(
      c(round(rnorm(24),1), rep(3,12)), nrow = 12, ncol = 3, byrow = F,
      dimnames = list(month.abb, LETTERS[1:3])
    )
    for (i in seq_len(nrow(m))) {
      m[i, 3] = sprintf(
        if_else(i == 1,
                '<input type="radio" name="%s" value="%s" checked="checked"/>',
                '<input type="radio" name="%s" value="%s"/>'),
        "C", month.abb[i]
      )
    }
    m
    output$foo = DT::renderDataTable(
      m, escape = FALSE, selection = 'none', server = FALSE,
      options = list(dom = 't', paging = FALSE, ordering = FALSE)
    )
    output$test <- renderPrint(str(input$C))
  }
)


来源:https://stackoverflow.com/questions/43738851/adding-radiobutton-to-select-a-datatable-row-in-shiny

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!