DT根据单独的数据帧将背景色应用于单元格

时间:2019-05-13 04:23:25

标签: r dt

我有一张想要将背景色应用于单个单元格的表。颜色与显示的数据没有明显的直接关系,并且在单独的数据集中指定。

我将如何应用以下指定的背景单元格颜色:

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

到如下数据表:

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

干杯, 卢克

1 个答案:

答案 0 :(得分:4)

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")) 

enter image description here

或者,使用循环:

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