2017-10-11 55 views
0

少一个闪亮的应用程序,我有一个datatable一列数字,其中出于安全原因,一些值已被抑制,我们要替换这些带有特定字符串,这里我会打电话给"my_string"。当这列排序,这些抑制值需要排序,尽管它们是小于所有实际数字。在该列中的所有的值都是正的,除了已被编码为-1的抑制值。[R闪亮的数据表代替数字用绳子和排序为比数值

我已经试过重新编码-1"my_string"(其要挟的列character),并使用natural plug-in的字符编码NUMERICS正确排序,但"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) 

enter image description here

回答

1

这可能是一个自定义格式/列更容易渲染功能。

见第二栏渲染的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) 
+0

完美,谢谢!查看通用数据表文档如何映射到R'DT'上下文也很有帮助。对于未来的参观者的注意事项 - 我已经列入'服务器= FALSE'在我的例子只是因为'natural'插件需要它,它实际上不是必需的这一解决方案。 –