首页 > 解决方案 > R-Shiny - 在表格中创建单选按钮,列可选

问题描述

我正在尝试在 Shiny 中构建一个使用单选按钮的表格。我需要特定于列的布局(而不是示例使用的特定行)。我在这里关注代码示例:https ://rstudio.github.io/DT/011-radio.html 。它似乎正在工作,但我无法在输出窗口中显示结果。

library(shiny)
library(DT)

c1 = "This is comment 1"
c2 = "This is comment 2"
c3 = "This is comment 3"
c4 = "This is comment 4"
c5 = "This is comment 5"
comments = list(c1,c2,c3,c4,c5)

ui <- fluidPage(
    tags$head(tags$style(HTML("#foo.tr.selected {background-color:red}"))),
    title = 'Radio buttons in a table',
    DT::dataTableOutput('foo'),
    verbatimTextOutput('sel')
)


  server <- function(input, output) {
    m = matrix(
      as.character(1:5), nrow = 5, ncol = 1, byrow = FALSE,
      dimnames = list(comments, LETTERS[1])
    )
    for (i in seq_len(nrow(m))) {
      m[i, ] = sprintf(
        '<input type="radio" name="%s" value="%s"/>',
        "AValue", m[i, ]
      )
    }
    m
    output$foo = DT::renderDataTable(
      m, escape = FALSE, selection = 'none', server = FALSE,
      options = list(dom = 't', paging = FALSE, ordering = FALSE),
      callback = JS("table.cols().every(function(i, tab, col) {
          var $this = $(this.node());
          $this.attr('id', this.data());
          $this.addClass('shiny-input-radiogroup');
        });
        Shiny.unbindAll(table.table().node());
        Shiny.bindAll(table.table().node());")
    )
    output$sel = renderPrint({
      str(sapply(comments, function(i) input[[i]]))
    })
  }

shinyApp(ui = ui, server = server)

我假设我的回调 Javascript 代码中有错误。我在代码中尝试了一些不同的变体,但我无法从单选按钮获得结果。谢谢!

标签: javascriptrshinydt

解决方案


推荐阅读