我正在编写R Shiny应用程序。我在DT DataTable上使用具有特定颜色的文本条目。当桌子求助时,颜色不会与正确的行保持在一起。相反,他们留在原地。
我假设我需要观察并对被重新排序/过滤的表事件做出反应。我该怎么做?
下面的示例代码。
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
列中设置颜色吗?这样:
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)