添加radiobutton以选择Shiny中的DataTable行

时间:2017-05-02 13:13:47

标签: javascript r shiny dt

我需要添加radiButtons来选择Data中的行,即选择radiobutton是否应该传递给输入。 我不能在DT中使用内置行选择。我真的需要使用radiobuttons来选择行。 这就是你想要的:wanted result for rows selection

使用https://yihui.shinyapps.io/DT-radio/我可以选择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))
}
)

结果是:partial result for columns selection

天真地,我试图删除m = t(m)并将行更改为回调中的列。这是行不通的,因为示例中的回调函数是将class和id添加到last,而没有列的对应项。

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

“脏”修复可能是使用div id和C类将整个数据表包装在shiny-input-radiogroup中:

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))
  }
)