与此非常相似:adding a column with TRUE/FALSE and showing that as a checkbox
library(shiny)
library(DT)
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,Rating=shinyInput(selectInput,nrow(mtcars),"selecter_",
choices=1:5, width="60px"))
}, selection='none',server = FALSE, escape = FALSE, options = list(
paging=TRUE,
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("selecter_",nrow(mtcars)))
})
}
))
请注意,如果您重新渲染表格,输入将不起作用,除非您添加一些额外的代码来取消绑定。
编辑:
假设表中的数据是反应性的,因此它会发生变化,并且表会重新呈现。您需要在这里按照@yihui 明确解除绑定:https://groups.google.com/forum/#!msg/shiny-discuss/ZUMBGGl1sss/zfcG9c6MBAAJ
所以你需要在 UI 中添加:
tags$script(HTML("Shiny.addCustomMessageHandler('unbind-DT', function(id) {
Shiny.unbindAll($('#'+id).find('table').DataTable().table().node());
})"))
然后在服务器中,每当您重新渲染数据表时,您都会触发该函数:
session$sendCustomMessage('unbind-DT', 'mytable')
colnames 参数是列名的向量,因此当您指定长度为 FALSE 的向量时,它会为您提供一个包含一列名为 FALSE 的表。我不确定从数据表中删除列名的直接方法。这本身就是一个很好的 SO 问题。