【问题标题】:R Shiny DataTables replace numeric with string and sort as being less than numeric valuesR Shiny DataTables用字符串替换数字并排序为小于数值
【发布时间】:2018-03-23 11:46:38
【问题描述】:

在一个 Shiny 应用程序中,我在 datatable 中有一列数字,出于安全原因,其中一些值已被禁止,我们想用特定字符串替换它们,这里我将其称为 "my_string"。在此列上排序时,这些抑制值需要进行排序,就好像它们小于所有实际数字一样。在此列中,所有值都是正数,除了被编码为-1 的抑制值。

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

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

这是我使用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)

【问题讨论】:

    标签: javascript r datatables shiny natural-sort


    【解决方案1】:

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

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

    以及 DataTables 文档: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)
    

    【讨论】:

    • 完美,谢谢!查看通用数据表文档如何映射到 R DT 上下文也很有帮助。给未来访问者的注意事项 - 我在示例中包含 server = FALSE 只是因为 natural 插件需要它,这个解决方案实际上不需要它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-06
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    相关资源
    最近更新 更多