在formattable中,背景颜色可以由不同的列决定吗

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

我在格式化表中工作,我喜欢颜色块的外观,但我不知道如何在该列中指定除渐变以外的任何颜色。我希望 color_tile 中的背景颜色由不同列中的值确定

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 有漂亮的色块,col3 的文本是基于第 4 列中的值的正确颜色,我如何将两者结合起来,根据不同列中的值选择漂亮的背景颜色。 “跨度”或颜色是否有更多选项?

使用下面的代码为 col3 设置您最喜欢的背景颜色。现在,我离开了你选择的那个。

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")))))))


我通过查看函数的代码发现这是可能的 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>