javascript - R Shiny DataTables 用字符串替换数字并按小于数字值排序

标签 javascript r datatables shiny natural-sort

在一个 Shiny 的应用程序中,我在数据表中有一列数字,出于安全原因,某些值已被抑制,我们希望用特定的字符串替换它们,在这里我将其称为“my_string”。在此列上排序时,这些抑制值需要按小于所有实际数字的方式进行排序。在此列中,除已编码为 -1 的抑制值外,所有值均为正值。

我尝试将 -1 重新编码为 "my_string"(将列强制为字符)并使用 natural plug-in对字符编码数字进行正确排序,但 "my_string" 的排序方式就好像它大于所有数值。

处理此问题的另一种可能方法可能是使用 JavaScript 回调将 -1 替换为字符串,但我不知道如何编写该脚本并将其正确添加到数据表中。

这是我使用 natural 插件的尝试。如果它按照我想要的方式工作,带有“my_string”的行将位于列表的底部而不是顶部。

# Example data, representing how the data comes to me
my_mtcars <- mtcars[1:6, 1:4]
my_mtcars[1, 4] <- -1

# Here I am recoding the -1
my_mtcars[my_mtcars == -1] <- 'my_string'

# This is our demo app.R
library(shiny)
library(DT)

ui <- fluidPage(
  dataTableOutput('example')
)

server <- function(input, output) {
  output$example <- renderDataTable(
    my_mtcars,
    server = FALSE,
    plugins = 'natural',
    options = list(columnDefs = list(list(type = 'natural', targets = '_all')))
  )
}

shinyApp(ui = ui, server = server)

enter image description here

最佳答案

使用自定义格式化程序/列渲染函数可能会更容易。

请参阅 DT 文档中的列渲染:https://rstudio.github.io/DT/options.html

数据表文档:https://datatables.net/reference/option/columns.render

my_mtcars <- mtcars[1:6, 1:4]
my_mtcars[1, 4] <- -1

formatSuppressedValues <- JS("
  function(data, type) {
    if (type !== 'display') return data;
    if (data !== -1) return data;
    return 'my_string';
  }
")

library(shiny)
library(DT)

ui <- fluidPage(
  DT::dataTableOutput('example')
)

server <- function(input, output) {
  output$example <- DT::renderDataTable(
    my_mtcars,
    server = FALSE,
    options = list(
      columnDefs = list(list(
        targets = '_all',
        render = formatSuppressedValues
      ))
    )
  )
}

shinyApp(ui = ui, server = server)

关于javascript - R Shiny DataTables 用字符串替换数字并按小于数字值排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46694351/

相关文章:

asp.net jquery datatables.net webmethod

jquery - 单击 : Disable and modify text of button inside DataTables

javascript - 如何将 Google 联系人列表拉入 Meteor 应用程序

javascript - 页面加载后如何删除或隐藏div

javascript - Angularjs: ngDialog 只绑定(bind)和修改对象;不是基本变量。

json - 将 geojson/json 文件读入 R 以便在 map 上绘制时遇到问题

javascript - JS Datatables - 从标题中的组合框中过滤表格

javascript - 更改 Canvas 大小时保留 svg 组的大小

r - 其他两列之间的唯一值列

r - 将重叠的多边形合并为单个多边形