当R Shiny DT数据表被排序/过滤时,如何确保行着色更新? [英] How to ensure row coloring updates when R Shiny DT datatable is sorted/filtered?
本文介绍了当R Shiny DT数据表被排序/过滤时,如何确保行着色更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写R Shiny应用程序。我在DT数据表中使用带有特定颜色的文本输入。重新使用表格时,颜色不会正确排列。相反,它们留在原处。
I am writing an R Shiny app. I use at DT datatable with specific colors for text entries. When the table is resorted the colors do not stay with their correct rows. Instead they stay in place.
我认为我需要观察并对表进行重新排序/过滤的事件并做出反应。我该怎么做?
I assume that I need to observe and react to the event of the table being reordered/filtered. How do I do that?
下面的示例代码。
library(shiny)
library(DT)
ui= shinyUI(fluidPage(
titlePanel("Test reorder DT datatave"),
sidebarLayout(
actionButton("button does nothing", "nothing")
,
mainPanel(
DT::dataTableOutput("mydt")
)
)
))
server <- function(input, output) {
output$mydt <- DT::renderDataTable({
dat <- data.frame(src=c(1,2,3), tgt=c("█", "█", "█"))
mycolors <- c("dodgerblue2", "grey", "firebrick2")
rgbcolors <- apply(grDevices::col2rgb(mycolors), 2,
function(rgb) sprintf("rgb(%s)", paste(rgb, collapse=",")))
column <- 2
jscode <- paste("function(row, data, index) {",
sprintf("var colors=%s;\n$(this.api().cell(index,
%s).node()).css('color', colors[index]);",
sprintf("[%s]", paste(sprintf("'%s'", rgbcolors),
collapse=", ")), column), "}", sep="\n")
datatable(dat, escape=FALSE,
options = list(rowCallback=JS(jscode))
)
})
}
shinyApp(ui = ui, server = server)
推荐答案
可以直接在 tgt
列中设置颜色吗?像这样:
Is it OK to set the colors directly in the tgt
column? Like this:
mycolors <- c("dodgerblue2", "grey", "firebrick2")
rgbcolors <- apply(grDevices::col2rgb(mycolors), 2,
function(rgb) sprintf("rgb(%s)", paste(rgb, collapse=",")))
tgt <- sprintf('<span style="color:%s">█</span>', rgbcolors)
dat <- data.frame(src=c(1,2,3), tgt=tgt)
datatable(dat, escape=FALSE)
这篇关于当R Shiny DT数据表被排序/过滤时,如何确保行着色更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文