在R闪亮数据表中添加动态UI元素

时间:2015-05-19 12:39:45

标签: r shiny

我正在生成包含一些结果的数据表。我希望用户能够点击特定行以显示详细信息。以下设置有效:

ui.R

library(DT)
shinyUI({
  basicPage(
    actionButton("compute", "Compute"),

    tags$div(id="blah", class="shiny-input-radiogroup", 
      dataTableOutput( "results" )
    ), 
    tags$h1(textOutput( "foo" ))
  )
})

server.R

library(DT)
server.fun <- function(input, output) {
  output$foo <- renderText({
    input$blah
  })

  output$results <- renderDataTable({
    if(input$compute) {
      results <- data.frame(ID=1:10, contents=letters[1:10])
      results$checkbox <- sprintf( '<input type="radio" name="blah" value="%d"/>', 1:10 )
      datatable(results, escape=FALSE)
    } else {
      NULL
    }
  })
}

单击单选按钮时,将执行操作(行号显示在底部)。这很好,并展示了我想要实现的目标。但是,我想有一个常规操作按钮,而不是一个单选按钮。以下代码不起作用,我的问题是:我怎样才能使它工作?

ui.R

library(DT)
shinyUI({
  basicPage(
    actionButton("compute", "Compute"),
    dataTableOutput( "results" ),
    tags$h1(textOutput( "foo" ))
  ) 
})

server.R

library(DT)

server.fun <- function(input, output) {
  output$foo <- renderText({
    input$blah
  })

  output$results <- renderDataTable({
    if(input$compute) {
      results <- data.frame(ID=1:10, contents=letters[1:10])
      results$checkbox <- 
        sprintf( '<button id="blah" type="button" class="btn btn-default action-button" value="%d">Do</button>', 1:10 )
      datatable(results, escape=FALSE)
    } else {
      NULL
    }
  })
}

1 个答案:

答案 0 :(得分:0)

如果有人需要它,我找到了使其成为表格中的动作按钮的方法。在这种情况下'?'单击并显示警告消息。这是代码:

output$factorsTable = DT::renderDataTable(
   DT::datatable({
      factorName <- c('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5', 'Factor 6', 'Factor 7', 'Factor 8', 'Factor 9', 'Factor 10')
      factorValues <- c('0.1','0.2','0.3','0.4','0.5','0.6','0.7','0.8','0.9','1')
      helpBtn <- '<button><b>?</b></button>'
      helpButton <- c(helpBtn,helpBtn,helpBtn,helpBtn,helpBtn,helpBtn,helpBtn,helpBtn,helpBtn,helpBtn)
      factors.data <- data.frame(factorName, factorValues,helpButton)    
      factors.data},    
   colnames = c('Factor','Value',,'Help'),  
   escape = FALSE,
   rownames = FALSE,
   selection= 'single',    
   options = list( searching=FALSE, paging =FALSE,                   
       columnDefs = list(
      list(
       targets=4,
       render=JS(
         "function(data, type, full) {",
         "return '<a class=\"btn btn-primary btn-sm\" onclick=\"alert(\\''+ full[0] +'\\')\"  href=#/' + '>' + '?' + '</a>';",

         "}"  
       )
     ))
     ),     
  class = "display",
  callback = JS('table.page(0).draw(false);')   
  )  
 )