How to give color to a given interval of rows of a DT table?

吃可爱长大的小学妹 提交于 2020-01-02 04:33:11

问题


I am using the DT library to visualize tables, but let's say I want to give a color to some rows like for example RED from row 1 to row 4:

Also it would be really nice to change the color of the text if it's possible. After hours of searching I found this function from library DT:

datatable(df, rownames = FALSE) %>%
  formatStyle(columns = "inputval", 
              background = styleInterval(c(0.7, 0.8, 0.9)-1e-6, c("white", "lightblue", "magenta", "white"))) 

But I need to give color to all columns not just a selected column like inputval in the code, can I give to columns value something like names(df) so it can give color to all columns? And styleInterval selects the values in table not the interval of rows, how can I do that so I can select the rows and give them a color?


回答1:


Something like this should do the job. Note that I coloured the rows 2:4 on purpose instead of 1:4 for more functionality:

library(shiny)
library(DT)

ui <- basicPage(
  mainPanel(DT::dataTableOutput('mytable'))
)

server <- function(input, output,session) {

  output$mytable = DT::renderDataTable(    
    DT::datatable(mtcars,  options = list(
      pageLength = 25,
      rowCallback = JS('function(row, data, index, rowId) {',
                       'console.log(rowId)','if(rowId >= 1 && rowId < 4) {',
                       'row.style.backgroundColor = "pink";','}','}')
    )
    )
  ) 




}
runApp(list(ui = ui, server = server))

Edit: Dynamically colour rows: here I simply used sub to substitute for the range to colour the rows

library(shiny)
library(DT)

fnc <- JS('function(row, data, index, rowId) {',
                    'console.log(rowId)','if(rowId >= ONE && rowId < TWO) {',
                    'row.style.backgroundColor = "pink";','}','}')

ui <- basicPage(
  sliderInput("colorrows", "Which to color:",min = 0, max = 10, value = c(1,3)),
  mainPanel(DT::dataTableOutput('mytable'))
)

server <- function(input, output,session) {

  Coloring <- eventReactive(input$colorrows,{
    fnc <- sub("ONE",input$colorrows[1],fnc)
    fnc <- sub("TWO",input$colorrows[2],fnc)
    fnc
  })

  output$mytable = DT::renderDataTable(
    DT::datatable(mtcars,  options = list(pageLength = 25,rowCallback = Coloring())
    )
  )
}
runApp(list(ui = ui, server = server))



来源:https://stackoverflow.com/questions/45542144/how-to-give-color-to-a-given-interval-of-rows-of-a-dt-table

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