Search code examples
rformattingconditional-statementsgtablegrob

R tablegrob conditional formating for setting colors based on column values


Is there a way to conditional format a column of a tableGrob or gtable object and color (Red, yellow or Green) it based on a conditional format? For instance:

library(gridExtra)
library(grid)
d = head(iris, 20)
d
grob=tableGrob(d)

I wish to change Sepal.Width and color it based on the values of Petal.Length. If Petal.Length = 1.1 then set it to red, if it is 1.4 then set it to yellow and if it is 1.7 set it to green.


Solution

  • The condformat package can be used for that and its syntax is quite self-explanatory, I believe:

    library(condformat)
    data(iris)
    condformat(head(iris, 20)) %>%
      rule_fill_discrete(
        columns = Sepal.Width,
        expression = Petal.Length,
        colours = c("1.1" = "red", "1.4" = "yellow", "1.7" = "green")) %>%
      condformat2grob()
    

    result