如何在RShiny DT中禁用指定单元格的编辑权限?
如何用RShiny DT通过行列索引禁用特定单元格的编辑权限
完全可以通过行列索引精准禁用DT表格中特定单元格的编辑权限,针对你给出的示例,下面提供两种可行方案:
方案1:预先指定禁用的单元格坐标
先定位到包含"Mary"的单元格的行列索引(注意DT在JavaScript中使用0-based索引,需要把R中的1-based索引转换为0-based),再通过editable参数配置禁用该单元格:
library(shiny) library(DT) dat <- data.frame( userName = c("John", "Mary", "Mike"), start = c("06/08/2019", "01/01/2019", "23/10/2019"), stringsAsFactors = FALSE ) ui <- fluidPage( titlePanel("Editable Datatable Example"), DTOutput("userTable") ) server <- function(input, output, session) { # 转换为DT使用的0-based索引 target_row <- which(dat$userName == "Mary") - 1 # R中行号为2,对应JS的1 target_col <- which(colnames(dat) == "userName") - 1 # R中列号为1,对应JS的0 output$userTable <- renderDT({ datatable( dat, editable = list( target = "cell", # 启用单元格级别的编辑控制 disable = list( cells = list(list(row = target_row, col = target_col)) # 指定禁用的单元格 ) ), rownames = FALSE ) }) observeEvent(input$userTable_cell_edit, { cat("Edited value:", input$userTable_cell_edit$value, "\n") }) } shinyApp(ui = ui, server = server)
方案2:用JS函数动态判断禁用条件
如果需要更灵活的判断逻辑(比如根据单元格内容或动态数据),可以使用JavaScript函数指定禁用规则:
library(shiny) library(DT) dat <- data.frame( userName = c("John", "Mary", "Mike"), start = c("06/08/2019", "01/01/2019", "23/10/2019"), stringsAsFactors = FALSE ) ui <- fluidPage( titlePanel("Editable Datatable Example"), DTOutput("userTable") ) server <- function(input, output, session) { output$userTable <- renderDT({ datatable( dat, editable = list( target = "cell", disable = JS( "function(cell, data) {", " // 禁用第2行第1列的单元格(0-based索引)", " return cell.row === 1 && cell.col === 0;", "}" ) ), rownames = FALSE ) }) observeEvent(input$userTable_cell_edit, { cat("Edited value:", input$userTable_cell_edit$value, "\n") }) } shinyApp(ui = ui, server = server)
说明
- 两种方案都会让包含"Mary"的单元格变为不可编辑状态,其余单元格保持可编辑
- DT的
editable参数接受列表配置,当target设为cell时,可以通过disable精准控制单个或多个单元格的编辑权限 - 若要禁用多个单元格,只需在
cells列表中添加多个list(row = x, col = y)对象即可
内容的提问来源于stack exchange,提问作者Odrai
相关产品推荐
相关产品推荐

