How to combine formatter and color_tile functions in a table using formattable

816 views Asked by At

I need to make a report with a table where a column will have a background and font colors depending on each row value. I have success using formatter or color_tile when they are isolated. But I need to use both at the same time.

Example:

col1 <- c(2.0, 3.3,6.3,1.5)
col2 <- c(4.7, 4.3, 2.5,1.9)
mydata <- data.frame(col1, col2)

customGreen = "#0d6d36"
customGreen0 = "#DeF7E9"

With the code below I can set the font color for column 2:

formattable(mydata, 
            align =c("l","c","c"),
            list(
              `col2` = formatter("span",style = x ~ style(color = ifelse(mydata$col2 >=3, "red","black")))
            )
)

font color

With the code below I can set the background color for column 2:

formattable(mydata, 
            align =c("l","c","c"),
            list(
              `col2` = color_tile(customGreen0, customGreen)
            )
)

enter image description here

But I canĀ“t set font color and background color at the same time. Any ideas?

1

There are 1 answers

0
tamtam On BEST ANSWER

Try to define your own formatter with the formatter function and combine background color with font color.

formatter
The color_tile effect is defined by display, padding, border-radius and background-color. And color sets the rules for font colors.

custom_format <- formatter(.tag = "span", style = function(x) style(
                                                   display = "block", 
                                                   padding = "0 4px", 
                                                   `border-radius` = "4px", 
                                                   `background-color` = csscolor(gradient(as.numeric(x), 
                                                                                          customGreen, customGreen0)),
                                                   color = ifelse(x >= 3, "red","black")))

use custom function

formattable(mydata, 
            align =c("l","c","c"),
            list(
              `col2` = costum_format))

output
enter image description here