Change Colors of Data Table

clrs_df is about taking the colorRamp which is a matrix, changing it to a dataframe, and pasting the rgb elements together to make rgb params

library(tidyverse)
library(DT)
mtcars$mpg


(brks <- quantile(mtcars$mpg, probs = seq(.05, .95, .01), na.rm = TRUE)) # provide numeric vector
(max_val <-max(mtcars$mpg,na.rm=TRUE))

(clrs_rmp <- colorRamp(c("red","green"))(c(0,brks/max_val)))

 (clrs_df <- clrs_rmp %>% 
  as_tibble(.name_repair ="minimal") %>% 
  setNames(nm=c("r","g","b")) %>% 
  mutate_all(~as.character(round(.,digits=0)))  %>% mutate(mycolor=paste0("rgb(",
                                                                          paste(r,g,b,sep = ","),
                                                                          ")")))
(clrs <- pull(clrs_df,mycolor))

DT::datatable(mtcars,rownames=TRUE) %>%
  formatStyle(colnames(mtcars), backgroundColor = styleInterval(brks, clrs))
1 Like