简体   繁体   中英

Shiny DT Styling Cell colors

I am attempting to load a file perform various preprocessing steps including subsetting the data. I am doing this all in a single reactive function and then assigning the various formated dataframes to a list to "export" out of the render function. The challenge I am running into when I display the tables renderDT only likes a data frame object, which was ok until I tried to figure out how to color certain cells. All the examples I found for styling cells requires a datatable object not a dataframe. See example: https://rstudio.github.io/DT/010-style.html

I am trying to color column C based on the following rules [1,10] = green, [11,19] = yellow, and [20,25] = red. I appreciate any suggestions on how to modify renderDT to allowing stlying of cells. Also does anyone if there is a way to change the font size inside the table?

require(readxl)
require(openxlsx)

 mydata<-structure(list(A = c(2, 2, 2, 6, 7, 8, 6, 7, 8, 6, 7, 8, 1, 1, 
 1, 1, 2), B = c("A", "A", "N", "O", "L", "L", "O", "L", "L", 
 "O", "L", "L", "A", "N", "N", "N", "A"), C = c(1, 2, 3, 4, 5, 
 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 20, 24)), class = "data.frame", row.names = c(NA, 
 -17L))

 runApp(
  list(
    ui = fluidPage(
      titlePanel("Import QUEST, Design, & Mitigation Lists"),
      sidebarLayout(
        sidebarPanel(
          fileInput('file1', 'Choose QUEST xlsx formatted file',
                    accept = c(".xlsx")
                   )),
        mainPanel(
          tabsetPanel(type = "tab",
                      tabPanel("Tab1", DTOutput('first')),
                      tabPanel("Tab2", DTOutput('second'))
                     )))),
    server = function(input, output){
      mydata1 <- reactive({
        req(input$file1)
        inFile <- input$file1
        mydata<-read_excel(inFile$datapath, 1)
        
        data1<-mydata[which(mydata<3),]
        data2<-mydata[which(mydata>6),]
        quest<-list(data1,data2)
        quest })
        
        output$first <- renderDT({as.data.frame(mydata1()[1])})
        
        output$second <- renderDT({as.data.frame(mydata1()[2])})
      
    }
))
shinyApp(ui, server)

As you said, you need to style a datatable object and pass this object to the renderDT function.

Any other arguments you want to pass to the renderDT now need to be moved to the DT::datatable constructor, see examples in this other post .

For font-size, see also this other post .

You have to pass a datatable in renderDT :

output$first <- renderDT({
  datatable(as.data.frame(mydata1()[1])) %>% 
      formatStyle(
        columns = "C", 
        backgroundColor = styleInterval(c(1,11,20), c("white", "red", "green", "yellow"))
      )
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM