Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I know that the data tables can be colored by their value like a heatmap. But here the cells are shaded according to values from all columns.

library(DT)

df = iris[1:4]

brks <- quantile(df, probs = seq(.05, .95, .05), na.rm = TRUE)

clrs <- round(seq(255, 40, length.out = length(brks) + 1), 0) %>%

  {paste0("rgb(255,", ., ",", ., ")")}

datatable(df) %>% formatStyle(names(df), backgroundColor = styleInterval(brks, clrs))

But what I need is to color column cells according to the values for each column. 

Does anyone know how to achieve that using the DT package? 

1 Answer

0 votes
by (108k points)

Let me inform you that yes, for each column, you can calculate breaks, assign colors, and apply a style:

library(DT)

library(viridis)

df = iris[1:4]

brks1 <- quantile(df$Sepal.Length, probs = seq(.05, .95, .05), na.rm = TRUE)

clrs1 <- viridis::viridis(n=length(brks1)+1, alpha=.5, direction = -1)

brks2 <- quantile(df$Petal.Length, probs = seq(.05, .95, .05), na.rm = TRUE)

clrs2 <- viridis::inferno(n=length(brks2)+1, alpha=.5, direction = -1)

datatable(df) %>% 

  formatStyle("Sepal.Length", backgroundColor = styleInterval(brks1, clrs1)) %>% 

  formatStyle("Petal.Length", backgroundColor = styleInterval(brks2, clrs2))

If you are a beginner and want to know more about R then do check out the R programming tutorial that will help you out in a better way. 

Browse Categories

...