How to ensure row coloring updates when R Shiny DT datatable is sorted/filtered?

為{幸葍}努か 提交于 2019-12-11 10:17:11

问题


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?

Sample code below.

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)

回答1:


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


来源:https://stackoverflow.com/questions/47740337/how-to-ensure-row-coloring-updates-when-r-shiny-dt-datatable-is-sorted-filtered

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!