Colouring specific table cells across different rows and columns in a gtsummary table using R and gtable

I am trying to colour specific cells in a gtsummary table of the mtcars data set.
The code below provides a gtsummary table with 4 columns, the first referring to the variables, and the remaining three columns referring to the three levels of the “cyl” factor.

The objective is to be able to pinpoint specific cells and assign to them a specific background colour. For instance, column 3, row 3 is the intersection of cyl = 6 and the value for disp for cyl = 6. I want that cell to be red, and the cell corresponding to cyl = 8 and the row 6 (variable wt) to be orange.

I have come across other pages where it is shown how you can colour an entire column in one colour, but have not found how you can target specific cells across columns with a specific colour, based on their location, value, or even text.

Any help would be much appreciated.


library(gtsummary)

library(tidyverse)

library(reprex)

mtcars %>%
  tbl_summary(by = cyl)

Leave a Comment