切换(即 hide/unhide)数据表中的行

Toggle (i.e. hide/unhide) rows in datatable

有没有办法实现这个:我已经显示了一个数据表,如果选择了行索引并单击了切换按钮,我想切换特定的行。我只想隐藏该行,而不是完全从数据表中删除。 我得到了 ui 如下。服务器端如何实现?

library(shiny)
library(DT)

data <- data.frame(
    Name = c("Andy", "Bob", "Chad"),
    Job = c("Clerk", "Pilot", "Electrician")
)

ui <- fluidPage(
    
    box(id = "myBox", title = NULL, 
        selectInput(inputId = "row_index", label = "Row to Toggle", choices = c(1,2,3))
    ),
    actionButton(inputId = "button", label = "Show/Hide"),
    DT::dataTableOutput(('DTOut'))
)

server <- function(input, output) {
    
    output$DTOut <- DT::renderDataTable({
        data
    })
}
shinyApp(ui = ui, server = server)

这是一个方法。它需要在第一个位置有一列行索引。如果您不想显示行索引,请添加此列并将其隐藏。

library(shiny)
library(DT)

initComplete <- JS(
  "function(settings, json) {",
  "  var table = this.api();",
  "  var nrows = table.rows().count();",
  "  $('#button').on('click', function() {",
  "    var nrows_filtered = table.rows({search:'applied'}).count();",
  "    if(nrows_filtered === nrows) {",
  "      var selection = $('select[id=row_index] option').val();",
  "      var rowsToShow = [];",
  "      for(var i = 1; i <= nrows; ++i) {",
  "        if(i != selection) rowsToShow.push('^' + i + '$');",
  "      }",
  "      var regex = '(' + rowsToShow.join('|') + ')';",
  "      table.column(0).search(regex, true).draw();",
  "    } else {",
  "      table.columns().search('').draw();",
  "    }",
  "  });",
  "}"
)

data <- data.frame(
  Name = c("Andy", "Bob", "Chad"),
  Job = c("Clerk", "Pilot", "Electrician")
)

ui <- fluidPage(
  
  wellPanel(id = "myBox", 
      selectInput(inputId = "row_index", label = "Row to Toggle", choices = c(1,2,3))
  ),
  actionButton(inputId = "button", label = "Show/Hide"),
  DTOutput("DTOut")
  
)

server <- function(input, output) {
  
  output$DTOut <- renderDT({
    datatable(data, options = list(initComplete = initComplete))
  })
  
}

shinyApp(ui = ui, server = server)