DT apply background colour to cell based on separate data frame

回眸只為那壹抹淺笑 提交于 2019-11-28 02:10:35

问题


I have a table to which I would like to apply background colours to individual cells. The colours have no obvious direct relationship with the data presented, and are specified in a separate data set.

How would I apply the background cell colours specified in:

set.seed(123)
colours2apply <- sample(x=c(rgb(1, 0, 0 ), rgb(1, 1, 0 ), rgb(0, 1, 1 )), 25, replace = T) %>% 
  matrix(nrow=5) %>% 
  data.frame()

> colours2apply
       X1      X2      X3      X4      X5
1 #FF0000 #FF0000 #00FFFF #00FFFF #00FFFF
2 #00FFFF #FFFF00 #FFFF00 #FF0000 #00FFFF
3 #FFFF00 #00FFFF #00FFFF #FF0000 #FFFF00
4 #00FFFF #FFFF00 #FFFF00 #FF0000 #00FFFF
5 #00FFFF #FFFF00 #FF0000 #00FFFF #FFFF00

to a datatable like:

datatable(iris[1:5, 1:5])

Cheers, Luc


回答1:


dat <- iris[1:5,1:5]
colours2apply <- sample(x=c(rgb(1, 0, 0 ), rgb(1, 1, 0 ), rgb(0, 1, 1 )), 25, replace = T) %>% 
  matrix(nrow=5) %>% 
  data.frame()

dat <- cbind(dat, colours2apply)

datatable(dat, 
          options = list(columnDefs = list(list(visible=FALSE, targets = 6:10)))) %>% 
  formatStyle(1, valueColumns = 6, backgroundColor = JS("value")) %>%
  formatStyle(2, valueColumns = 7, backgroundColor = JS("value")) %>%
  formatStyle(3, valueColumns = 8, backgroundColor = JS("value")) %>%
  formatStyle(4, valueColumns = 9, backgroundColor = JS("value")) %>%
  formatStyle(5, valueColumns = 10, backgroundColor = JS("value")) 

Or, using a loop:

DT <- datatable(dat, 
                options = list(columnDefs = list(list(visible=FALSE, targets = 6:10))))
for(i in 1:5){
  DT <- DT %>%
    formatStyle(i, valueColumns = i+5, backgroundColor = JS("value"))
}
DT


来源:https://stackoverflow.com/questions/56105725/dt-apply-background-colour-to-cell-based-on-separate-data-frame

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