Color Palettes in datatables R

Viewed 163

Curious why we cant apply diverging type styling on datatables.

In the code below, iris has no NAs and for simplicity sake I want to apply a diverging scheme to the 150 entries. All columns would get the color applied to the Sepal.Length rank, but its trivial to do it by column...

library(DT);library(colorspace);library(dplyr)
data(iris)
dt=datatable(iris) 

for (x in colnames(iris)) {
  if(x=='Species')next
  dt=dt %>% 
    formatStyle(x, color = tolower(diverging_hsv(150)[rank(iris$Sepal.Length)]))
}

There is no reported error, but this does not work

Note different datasets with NAs mess up the coloring:

dt <- datatable(airquality) 

these=c('Wind','Ozone')
for (x in these) {
  #v <- full_seq(unique(airquality[[x]]), .1)
  v = airquality[[x]]
  cs <- diverging_hsv(length(v))
  dt <- dt %>% 
    formatStyle(x, backgroundColor = styleEqual(v, cs))
}
1 Answers

You don't seem to be able to pass a vector of values directly to the color argument of formatStyle() instead you can use the helper function styleEqual() to map values to colors 1 to 1:

library(DT)
library(colorspace)
library(dplyr)
library(tidyr)

dt <- datatable(iris) 

for (x in colnames(iris)) {
  if (x == 'Species') next 
  v <- full_seq(unique(iris[[x]]), .1)
  cs <- diverging_hsv(length(v))
  dt <- dt %>% 
    formatStyle(x, color = styleEqual(v, cs))
}
Related