In formattable, can the background colour be determined by a different column

1.4k Views Asked by At

I'm working in formattable and I like the look of colour tiles, but I can't figure out how specify the colour on anything other than the gradient within that column. I'd like the background colour as seen in color_tile to be determined by values in a different column

col1 <- c("a", "b", "c", "d")
col2 <- c(532, 123, 324, NA)
col3 <- c(532, 123, 324, NA)
col4 <- c(-1,    0,  +1, NA)
df   <- data.frame(col1, col2, col3, col4)

formattable(df,
            list(col1 = formatter("span", style = ~ style(color = "black",font.weight = "bold")),
                 col2 = color_tile("lightseagreen", "lightskyblue"),
                 col3 = formatter("span",
                                  style = ~style(color = ifelse(col4 == 1, "red",
                                                                ifelse(col4 == 0, "green",
                                                                       ifelse(col4 == -1, "yellow", "blue")))))
            ))

Col2 has nice colour tiles, the text of col3 is the right colour based on values in column 4, How can I combine the two, to get a nice background colour of choice based on values in a different column. Are there more options for "span" or color?

1

There are 1 best solutions below

1
On BEST ANSWER

Use the code below to set up the backgroup colours you like the most for col3. For now, I left the one you chose.

formattable(df,
            list(col1 = formatter("span", style = ~ style(color = "black",font.weight = "bold")),
                 col2 = color_tile("lightseagreen", "lightskyblue"),
                 col3 = formatter("span",
                                  style = ~style(display = "block", 
                                                 padding = "0 4px", 
                                                 `border-radius` = "4px", 
                                                 `background-color` = ifelse(col4 == 1, "red",
                                                                             ifelse(col4 == 0, "green",
                                                                                    ifelse(col4 == -1, "yellow", "blue")))))))

enter image description here


I found out that this was possible by looking at the code of the function color_tile:

> color_tile
function (...) 
{
    formatter("span", style = function(x) style(display = "block", 
        padding = "0 4px", `border-radius` = "4px", 
        `background-color` = csscolor(gradient(as.numeric(x), 
            ...))))
}
<bytecode: 0x00000225fccd6e08>
<environment: namespace:formattable>