DT apply background colour to cell based on separate data frame
Asked Answered
S

1

5

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])
Sassy answered 13/5, 2019 at 4:23 Comment(0)
P
6
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

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
Poser answered 13/5, 2019 at 6:34 Comment(1)
just curious is it necessary that color and values have to be a part of the same dataframe?Gillmore

© 2022 - 2024 — McMap. All rights reserved.