【问题标题】:How to ensure row coloring updates when R Shiny DT datatable is sorted/filtered?对 R Shiny DT 数据表进行排序/过滤时,如何确保行着色更新?
【发布时间】:2017-12-10 15:30:33
【问题描述】:

我正在编写一个 R Shiny 应用程序。我在 DT 数据表中使用特定颜色的文本条目。重新使用表格时,颜色不会保留在正确的行中。相反,它们会留在原地。

我假设我需要观察表被重新排序/过滤的事件并做出反应。我该怎么做?

下面的示例代码。

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("&#9608;", "&#9608;", "&#9608;"))

  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 列中设置颜色,而不是使用回调。会不会出问题?

标签: r shiny dt


【解决方案1】:

直接在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">&#9608;</span>', rgbcolors)
dat <- data.frame(src=c(1,2,3), tgt=tgt)
datatable(dat, escape=FALSE)

【讨论】:

  • 完美。谢谢!
猜你喜欢
  • 2021-03-27
  • 2021-11-20
  • 2021-03-17
  • 2019-07-17
  • 2019-11-25
  • 2018-05-23
  • 1970-01-01
  • 2012-04-01
  • 2021-08-22
相关资源
最近更新 更多