下面的应用程序包含一个数据表iris
启用行选择的数据集。我想专门禁用前 3 行的选择。我可以使用发布的解决方案来做到这一点here。当表在应用程序启动时初始化时,该解决方案工作正常:
但是,当您对列上的行进行排序时,例如在Species
按降序排列,它禁用观察值 101、102 和 103,因为排序后它们现在是表的前 3 行:
我猜发生这种情况是因为rowCallback
is displayIndex
禁用行。所以在启动时,displayIndex
0、1 和 2 分别对应于 iris 数据集中的观测值 1、2 和 3,行回调会禁用它们的行选择,因为indices.indexOf(displayIndex) > -1
is true
对于这些行。但排序之后Species
, displayIndex
0、1 和 2 分别对应于观测值 101、102 和 103,因此回调会禁用它们。
为了解决这个问题,我尝试通过更改来禁用基于行名的行displayIndex
in the rowCallback
功能为dataIndex
。但是,这会造成一些奇怪的情况,每次我在不同的列上进行筛选时,附加行都会被禁用。这是表格首次排序后的示例Sepal.Length
, then Sepal.Length
然后最后Petal.Length
:
这是重现上述内容的代码:
library(DT)
library(shiny)
disabled_rows = c(1,2,3)
#NOTE: displayIndex changed to dataIndex
rowCallback <- c(
"function(row, data, displayNum, dataIndex){",
sprintf(" var indices = [%s]", toString(disabled_rows - 1)),
" if(indices.indexOf(dataIndex) > -1){",
" $(row).find('td').addClass('notselectable').css({'background-color': '#eee', 'color': '#bbb'});",
" }",
"}"
)
get_selected_rows <- c(
"var id = $(table.table().node()).closest('.datatables').attr('id');",
"table.on('click', 'tbody', function(){",
" setTimeout(function(){",
" var indexes = table.rows({selected:true}).indexes();",
" var indices = Array(indexes.length);",
" for(var i = 0; i < indices.length; ++i){",
" indices[i] = indexes[i];",
" }",
" Shiny.setInputValue(id + '_rows_selected', indices);",
" }, 0);",
"});"
)
drag_selection <- c(
"var dt = table.table().node();",
"$(dt).selectable({",
" distance : 10,",
" selecting: function(evt, ui){",
" $(this).find('tbody tr').each(function(i){",
" if($(this).hasClass('ui-selecting')){",
" table.row(i).select();",
" }",
" });",
" }",
"}).on('dblclick', function(){table.rows().deselect();});"
)
shinyApp(
ui = fluidPage(
tags$head(tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js")),
DTOutput('table')
),
server = function(input, output, session) {
output$table <- renderDT({
datatable(
iris,
callback = JS(get_selected_rows),
class = 'hover row-border order-column',
options = list(
rowCallback = JS(rowCallback),
select = list(style = "multi", selector = "td:not(.notselectable)")
),
extensions = "Select", selection = 'none'
)
}, server = F)
observe({
print(input$table_rows_selected)
})
}
)
我不知道为什么要改变displayIndex
to dataIndex
不起作用,我不知道还能尝试什么。 DataTables 的定义dataIndex
范围here由于我对 DT 插件不太熟悉,所以对我来说很模糊,所以我将不胜感激。
EDIT:我还尝试直接基于 rowname 禁用,如下所示:
rowCallback <- c(
"function(row, data, displayNum, displayIndex){",
" var indices = [0, 2, 4, 15]",
" if(indices.indexOf(data[0]) > -1){",
" $(row).find('td').addClass('notselectable');",
" }",
"}"
)