闪亮的数据表过滤器盒

时间:2019-02-11 09:03:07

标签: r shiny shinydashboard dt

我创建了一个表格,该表格的外观与屏幕截图相同。 如何在列表中选择多个特定项,如何添加一个像过滤器一样的Excel?

enter image description here

enter image description here

代码如下:

<div class="one">Hello World</div>
<div class="two">Hello World</div>

1 个答案:

答案 0 :(得分:1)

library(DT)

dat <- iris

sketch <- htmltools::tags$table(
  tableHeader(c("",names(dat))),
  tableFooter(rep("", 1+ncol(dat)))
)

js <- c(
  "function(){", 
  "  this.api().columns().every(function(){",
  "    var column = this;",
  "    var select = $('<select multiple=\"multiple\"><option value=\"\"></option></select>')",
  "      .appendTo( $(column.footer()).empty() )", 
  "      .on('change', function(){",
  "        var vals = $('option:selected', this).map(function(index,element){",
  "          return $.fn.dataTable.util.escapeRegex($(element).val());",
  "        }).toArray().join('|');",
  "        column.search(vals.length > 0 ? '^('+vals+')$' : '', true, false).draw();",
  "      });",
  "    column.data().unique().sort().each(function(d,j){",
  "      select.append('<option value=\"'+d+'\">'+d+'</option>')",
  "    });",
  "  });",
  "}")

datatable(dat, container=sketch, 
          options = list(
            initComplete = JS(js)
          )
)

enter image description here

编辑

行名是字符串,然后按以下顺序排序:1、10、100,...。不好。使用以下代码,它们不会被排序,这更好:

js <- c(
  "function(){", 
  "  this.api().columns().every(function(i){",
  "    var column = this;",
  "    var select = $('<select multiple=\"multiple\"><option value=\"\"></option></select>')",
  "      .appendTo( $(column.footer()).empty() )", 
  "      .on('change', function(){",
  "        var vals = $('option:selected', this).map(function(index,element){",
  "          return $.fn.dataTable.util.escapeRegex($(element).val());",
  "        }).toArray().join('|');",
  "        column.search(vals.length > 0 ? '^('+vals+')$' : '', true, false).draw();",
  "      });",
  "    var data = column.data();",
  "    if(i == 0){",
  "      data.each(function(d,j){",
  "        select.append('<option value=\"'+d+'\">'+d+'</option>');",
  "      });",
  "    }else{",
  "      data.unique().sort().each(function(d,j){",
  "        select.append('<option value=\"'+d+'\">'+d+'</option>');",
  "      });",
  "    }",
  "  });",
  "}")