How to change the cell color of a cell of an R Shiny data table dependent on it's value?

前端 未结 2 1110
鱼传尺愫
鱼传尺愫 2021-01-06 10:09

I am attempting to change the cell color of cells of an R Shiny data table dependent on their value. As an example, I\'ve created the following app:

# ui.R

         


        
相关标签:
2条回答
  • 2021-01-06 10:43

    Here are two ideas:

    I want all cells containing integers to be colored red

    (1) Mark integers using Javascript:

    library(DT)
    df <- head(iris)
    df %>% 
      datatable %>% 
      formatStyle(1:4, color = JS("value % 1 === 0 ? 'red' : ''"))
    

    Selectively, I'd like to color only the cells at row 2 column 2 and row 5 column 1

    (2) Mark cells using hidden value columns:

    m <- matrix(F, ncol = ncol(df)-1, nrow = nrow(df))
    m[rbind(c(2,2),c(5,1))] <- TRUE
    df %>% 
      cbind(m) %>% 
      datatable(
        options=list(columnDefs = list(list(visible=FALSE, targets=1:4+ncol(df)))),
      ) %>% 
      formatStyle(
        columns = 1:4, 
        valueColumns = 1:4+ncol(df), 
        color = styleEqual(c(1,0), c("red", "black"))
      )
    

    I'm abstracting from Shiny, since this seems to be a datatable question. Also, there may be better options.

    0 讨论(0)
  • 2021-01-06 10:51

    This page has a bunch of tips for formatting DT data tables: https://rstudio.github.io/DT/010-style.html

    For your specific question, there's the function formatStyle that allows you to set aesthetics based on specific values in the table:

    library(DT)
    options(DT.options = list(pageLength = 5))
    df = as.data.frame(cbind(matrix(round(rnorm(50), 3), 10), sample(0:1, 10, TRUE)))
    
    # style V6 based on values of V6
    datatable(df) %>% formatStyle(
        'V6',
        backgroundColor = styleEqual(c(0, 1), c('gray', 'yellow'))
    )
    
    # style V1 based on values of V6
    datatable(df) %>% formatStyle(
        'V1', 'V6',
        backgroundColor = styleEqual(c(0, 1), c('gray', 'yellow'))
    )
    
    0 讨论(0)
提交回复
热议问题