在一个 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)
最佳答案
使用自定义格式化程序/列渲染函数可能会更容易。
请参阅 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/