首頁  >  問答  >  主體

在 R 中使用模糊搜尋和 Shiny:綜合指南

我正在嘗試在 DT 資料表中使用此 JS 腳本(來自此網站:https://datatables.net/blog/2021-09-17):

var fsrco = $('#fuzzy-ranking').DataTable({
    fuzzySearch: {
        rankColumn: 3
    },
    sort: [[3, 'desc']]
});
 
fsrco.on('draw', function(){
    fsrco.order([3, 'desc']);
});

使用此腳本標記:

“//cdn.datatables.net/plug-ins/1.11.3/features/fuzzySearch/dataTables.fuzzySearch.js”

我想將其合併到 Shiny 應用程式中的 DT 資料表函數中,其中使用排名順序應用模糊搜尋(頂部相似度較高),但是,我不希望顯示排名列。

類似這樣,但不顯示排名列。

一些基本的常規範例:

    library(shiny)
    library(DT)
    js <- c(
      "  var fsrco = $('#fuzzy-ranking').DataTable({",
      "    fuzzySearch: {",
      "        rankColumn: 3",
      "    },",
      "    sort: [[3, 'desc']]",
      "});",
      "fsrco.on('draw', function(){",
      "    fsrco.order([3, 'desc']);",
      "});"
)
    ui <- fluidPage(
      DTOutput("table")
    )
    server <- function(input, output, session){
      output[["table"]] <- renderDT({
        datatable(
          iris,
          selection = "none",
          editable = TRUE, 
          callback = JS(js),
          extensions = "KeyTable",
          options = list(
            keys = TRUE,
            url = "//cdn.datatables.net/plug-ins/1.11.3/features/fuzzySearch/dataTables.fuzzySearch.js"
          )
        )
      })
    }
    shinyApp(ui, server)

P粉924915787P粉924915787184 天前398

全部回覆(1)我來回復

  • P粉310931198

    P粉3109311982024-04-02 12:56:23

    這個插件是一個舊插件,它不適用於最新版本的 DataTables。

    但我們可以採用計算相似度的 JavaScript 函數,並透過 SearchBuilder 擴充功能在自訂搜尋中使用它。

    首先,複製此 JavaScript 程式碼並將其儲存在名稱 levenshtein.js 下:

    /*
    BSD 2-Clause License
    
    Copyright (c) 2018, Tadeusz Łazurski
    All rights reserved.
    
    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
    
    * Redistributions of source code must retain the above copyright notice, this
      list of conditions and the following disclaimer.
    
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
    FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    */
    
    function levenshtein(__this, that, limit) {
      var thisLength = __this.length,
        thatLength = that.length,
        matrix = [];
    
      // If the limit is not defined it will be calculate from this and that args.
      limit = (limit || (thatLength > thisLength ? thatLength : thisLength)) + 1;
    
      for (var i = 0; i < limit; i++) {
        matrix[i] = [i];
        matrix[i].length = limit;
      }
      for (i = 0; i < limit; i++) {
        matrix[0][i] = i;
      }
    
      if (Math.abs(thisLength - thatLength) > (limit || 100)) {
        return prepare(limit || 100);
      }
      if (thisLength === 0) {
        return prepare(thatLength);
      }
      if (thatLength === 0) {
        return prepare(thisLength);
      }
    
      // Calculate matrix.
      var j, this_i, that_j, cost, min, t;
      for (i = 1; i <= thisLength; ++i) {
        this_i = __this[i - 1];
    
        // Step 4
        for (j = 1; j <= thatLength; ++j) {
          // Check the jagged ld total so far
          if (i === j && matrix[i][j] > 4) return prepare(thisLength);
    
          that_j = that[j - 1];
          cost = this_i === that_j ? 0 : 1; // Step 5
          // Calculate the minimum (much faster than Math.min(...)).
          min = matrix[i - 1][j] + 1; // Devarion.
          if ((t = matrix[i][j - 1] + 1) < min) min = t; // Insertion.
          if ((t = matrix[i - 1][j - 1] + cost) < min) min = t; // Substitution.
    
          // Update matrix.
          matrix[i][j] =
            i > 1 &&
            j > 1 &&
            this_i === that[j - 2] &&
            __this[i - 2] === that_j &&
            (t = matrix[i - 2][j - 2] + cost) < min
              ? t
              : min; // Transposition.
        }
      }
    
      return prepare(matrix[thisLength][thatLength]);
    
      function prepare(steps) {
        var length = Math.max(thisLength, thatLength);
        var relative = length === 0 ? 0 : steps / length;
        var similarity = 1 - relative;
        return {
          steps: steps,
          relative: relative,
          similarity: similarity
        };
      }
    }
    

    現在,這是 R 程式碼:

    library(DT)
    
    dtable <- datatable(
      iris,
      extensions = "SearchBuilder",
      options = list(
        dom = "Qlfrtip",
        searchBuilder = list(
          conditions = list(
            string = list(
              fuzzy = list(
                conditionName = "Fuzzy search",
                init = JS(
                  "function (that, fn, preDefined = null) {",
                  "  var el =  $('').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, pattern) {",
                  "  var fuzzy = levenshtein(value, pattern[0]);",
                  "  return fuzzy.similarity > 0.25;",
                  "}"
                )
              )
            )
          )
        )
      )
    )
    
    path <- normalizePath("path/to") # the folder containing levenshtein.js
    dep <- htmltools::htmlDependency(
      "Levenshtein", "1.0.0", 
      path, script = "levenshtein.js")
    dtable$dependencies <- c(dtable$dependencies, list(dep))
    dtable
    

    必須選擇相似度的閾值。這裡我取的是0.25

    return fuzzy.similarity > 0.25;
    

    編輯

    要在 Shiny 中使用,請使用 server=FALSE:

    renderDT({
      dtable
    }, server = FALSE)
    

    回覆
    0
  • 取消回覆