Search code examples
rformattable

R Formattable apply two format to an area


I'm trying to use formattable awesome package and get a table with percentages and color scaled on multiple columns.

Here is the code

set.seed(123)
df <- data.frame(id = 1:10, 
                 a = rnorm(10), b = rnorm(10), c = rnorm(10))

df$a <- percent(df$a)
df$b <- percent(df$b)
df$c <- percent(df$c)


table_with_percent_but_color_not_scaled <- formattable(df, list(a = color_tile("transparent", "pink")
                     , b= color_tile("transparent", "pink")
                     , c= color_tile("transparent", "pink")))

table_with_color_scaled_but_not_percent <- formattable(df, list(area(col = 2:4)  ~  color_tile("transparent","pink")))

Problem is that table_with_color_scaled_but_not_percent don't keep the percentage format :

enter image description here

and table_with_percent_but_color_not_scaled don't keep the same scale for coloring the colors:

enter image description here

Ideally I would like to use the area functionality, since my df number of columns and name will change in my final code. Any idea ? Thanks!


Solution

  • I had the same problem a while back and had to create my own formatter. Here's the formatter with code used to create a table similar to yours. Just adjust the tags inside the style.

    library(tidyverse)
    library(formattable)
    
    colorbar <- function(color = "lightgray", fun = "comma", digits = 0) {
      fun <- match.fun(fun)
      formatter("span", x ~ fun(x, digits = digits),
                style = function(y) style(
                  display = "inline-block",
                  direction = "rtl",
                  "border-radius" = "4px",
                  "padding-right" = "2px",
                  "background-color" = csscolor(color),
                  width = percent(proportion(as.numeric(y), na.rm = TRUE))
                )
      )
    }
    
    set.seed(123)
    df <- data.frame(id = as.factor(1:10), 
                     a = rnorm(10), b = rnorm(10), c = rnorm(10)) %>%
      mutate_if(is.numeric, percent)
    
    tbl <- df %>%
      formattable(list(area(col = 2:4) ~ colorbar(color = "pink", fun = "percent", digits = 2))) %>%
      as.htmlwidget()
    

    If you have questions, let me know!