【问题标题】:Update R shiny datatable options without re-rendering在不重新渲染的情况下更新 R 闪亮的数据表选项
【发布时间】:2022-07-30 20:51:22
【问题描述】:

在 R Shiny 应用程序中,我想为用户提供更新数据表初始化选项的能力。例如,用户可能希望在某些情况下通过字符串文字搜索数据表内容,在其他情况下通过正则表达式搜索。

虽然实现此功能相当简单,但似乎没有办法在不重置列过滤器和搜索条目的情况下更新数据表的正则表达式选项。我想知道是否可以确保选项更新不会干扰搜索框和过滤器。下面是一个例子:

library(shiny)
library(DT)

ui <- fluidPage(

  sidebarLayout(
    
    sidebarPanel(
      checkboxInput("useRegex", "Use Regex?")
    ),

    mainPanel(
      dataTableOutput("DT")
    )

  )
)

server <- function(input, output, session) {

  output$DT <- renderDataTable({

    datatable(

      data = iris,

      options = list(
        search = list(regex = input$useRegex, caseInsensitive = TRUE)
      ),

      selection = "single",
      filter = "top"

    )

  })
}

shinyApp(ui = ui, server = server)

我意识到,当切换正则表达式选项时,可以保存数据表的状态,重新初始化,然后重新创建状态。这有效,但不可扩展。我想理想的解决方案可能会通过dataTableProxy 更新选项,类似于visNetwork 允许通过visNetworkProxy 更新选项。

【问题讨论】:

    标签: r shiny dt


    【解决方案1】:

    关于您提到的特定用例的评论:使用/不使用正则表达式进行搜索。

    SearchBuilder 扩展为字符串定义了多个搜索条件,例如“包含”、“开始于”、“结束于”。如果需要,您可以添加自定义标准。这里我添加了一个标准 "matches regex"

    library(DT)
    
    datatable(
      iris,
      extensions = "SearchBuilder",
      options = list(
        dom = "Qlfrtip",
        searchBuilder = list(
          conditions = list(
            string = list(
              regex = list(
                conditionName = "matches regex",
                init = JS(
                  "function (that, fn, preDefined = null) {",
                  "  var el =  $('<input/>').on('input', function() { fn(that, this) });",
                  "  if (preDefined !== null) {",
                  "     $(el).val(preDefined[0]);",
                  "  }",
                  "  return el;",
                  "}"
                ),
                inputValue = JS(
                  "function (el) {",
                  "  return $(el[0]).val();",
                  "}"
                ),
                isInputValid = JS(
                  "function (el, that) {",
                  "  return $(el[0]).val().length !== 0;",
                  "}"
                ),
                search = JS(
                  "function (value, regex) {",
                  "  var reg = new RegExp(regex, 'g');",
                  "  return reg.test(value);",
                  "}"
                )
              )
            )
          )
        )
      )
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 2020-09-14
      • 1970-01-01
      • 2017-10-14
      • 2015-09-08
      • 2021-06-19
      • 1970-01-01
      相关资源
      最近更新 更多