添加一个TRUE / FALSE列并将其显示为复选框

时间:2016-05-20 22:14:59

标签: r datatable shiny

我的列中包含TRUEFALSE

data("mtcars")
mtcars$Favorite <- "FALSE"

我有兴趣将此列(收藏夹)显示为闪亮的复选框。

runApp(list(
  ui = basicPage(
    h2('The mtcars data'),
    dataTableOutput('mytable')
  ),
  server = function(input, output) {
    output$mytable = renderDataTable({
      mtcars
    })
  }
))

来源:http://shiny.rstudio.com/articles/datatables.html

不确定如何使其发挥作用,非常感谢任何帮助。

1 个答案:

答案 0 :(得分:7)

这是你要找的吗?

library(shiny)
library(DT) # dev from github
runApp(list(
  ui = basicPage(
    h2('The mtcars data'),
    DT::dataTableOutput('mytable'),
    h2("Selected"),
    tableOutput("checked")
  ),

  server = function(input, output) {
    # helper function for making checkbox
    shinyInput = function(FUN, len, id, ...) { 
      inputs = character(len) 
      for (i in seq_len(len)) { 
        inputs[i] = as.character(FUN(paste0(id, i), label = NULL, ...)) 
      } 
      inputs 
    } 
    # datatable with checkbox
    output$mytable = DT::renderDataTable({
      data.frame(mtcars,Favorite=shinyInput(checkboxInput,nrow(mtcars),"cbox_"))
    }, server = FALSE, escape = FALSE, options = list( 
      paging=FALSE,
      preDrawCallback = JS('function() { 
Shiny.unbindAll(this.api().table().node()); }'), 
      drawCallback = JS('function() { 
Shiny.bindAll(this.api().table().node()); } ') 
    ) )
    # helper function for reading checkbox
    shinyValue = function(id, len) { 
      unlist(lapply(seq_len(len), function(i) { 
        value = input[[paste0(id, i)]] 
        if (is.null(value)) NA else value 
      })) 
    } 
    # output read checkboxes
    output$checked <- renderTable({
      data.frame(selected=shinyValue("cbox_",nrow(mtcars)))
    })
  }
))