I know you love formattable’s color_tile and color_bar. I do too. In my mind, these two features are among the best visualization methods in a tabular format. You may wonder if it’s possible use it together with kableExtra so you can have a nested table with awesome presentation at the same time. Here is how.

library(knitr)
library(kableExtra)
library(formattable)
library(dplyr)
mtcars[1:5, 1:4] %>%
  mutate(
    car = row.names(.),
    mpg = color_tile("white", "orange")(mpg),
    cyl = cell_spec(cyl, "html", angle = (1:5)*60, 
                    background = "red", color = "white", align = "center"),
    disp = ifelse(disp > 200,
                  cell_spec(disp, "html", color = "red", bold = T),
                  cell_spec(disp, "html", color = "green", italic = T)),
    hp = color_bar("lightgreen")(hp)
  ) %>%
  select(car, everything()) %>%
  kable("html", escape = F) %>%
  kable_styling("hover", full_width = F) %>%
  column_spec(5, width = "3cm") %>%
  add_header_above(c(" ", "Hello" = 2, "World" = 2))
Hello
World
car mpg cyl disp hp
Mazda RX4 21.0 6 160 110
Mazda RX4 Wag 21.0 6 160 110
Datsun 710 22.8 4 108 93
Hornet 4 Drive 21.4 6 258 110
Hornet Sportabout 18.7 8 360 175

Here is a little bit more explanation. Both formattable::color_tile and formattable::color_bar returns a function object which can take a numeric vector. That’s why you can put things like (mpg) after color_tile("white", "orange") as you can see in the mutate function. This way of using the function may look a little odd but is totally valid (, I think :P).

Also, if you are using it in this way, make sure you put escape = F in kable.

On the other hand, cell_spec() is a new function in kableExtra() to format cells before you pipe the table into kable. Note that you can either specify format (html or latex) in function or do that via options(knitr.table.format) so you don’t need to do it everytime. Please refer to the package vignette for details.

iris[1:10, ] %>%
  mutate(
    Species = cell_spec(Species, color = spec_color(1:10, option = "A"), link = "#",
                        tooltip = paste0("Sepal Length: ", Sepal.Length))
  ) %>%
  mutate_if(is.numeric, function(x){
    cell_spec(x, "html", color = spec_color(x), font_size = spec_font_size(x), bold = T)
  }) %>%
  kable("html", escape = F, align = "c") %>%
  kable_styling("condensed", full_width = F)
## Setting cell_spec format as html
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5.1 3.5 1.4 0.2 setosa
4.9 3 1.4 0.2 setosa
4.7 3.2 1.3 0.2 setosa
4.6 3.1 1.5 0.2 setosa
5 3.6 1.4 0.2 setosa
5.4 3.9 1.7 0.4 setosa
4.6 3.4 1.4 0.3 setosa
5 3.4 1.5 0.2 setosa
4.4 2.9 1.4 0.2 setosa
4.9 3.1 1.5 0.1 setosa