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

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?



Solution 1:[1]

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, pading, border-radius and background-color. And color sets the rules for font colors.

costum_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 costum function

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

output
enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tamtam