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

前端 未结 2 1107
鱼传尺愫
鱼传尺愫 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.

提交回复
热议问题