在 Shiny 中将单选按钮添加到 select 数据表行

Adding radiobutton to select a DataTable row in Shiny

我需要将 radiButtons 添加到数据中的 select 行,即应将选择的单选按钮传递给输入。 我不能在 DT 中使用内置行 selection。我真的需要使用单选按钮 select 该行。 这就是想要的:

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

结果是:

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

有什么想法吗?

"dirty" 修复可能是将整个数据表包装在 div 中,ID 为 Cshiny-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))
  }
)