Search code examples
rgridextragrob

How to theme a tableGrob object from gridExtra in r


I would like to re-use a theme/template/default for a tableGrob object from the gridExtra package in r.

library(gridExtra)

tableGrob(df, cols = c("Custom Name", "Custom Name2"), 
          show.rownames = FALSE, h.even.alpha = 0)

tableGrob(df2, cols = c("Different Name", "Different Name2"), 
          show.rownames = FALSE, h.even.alpha = 0)

Notice, I do not want to have to repeat show.rownames = FALSE and h.even.alpha = 0 multiple times. What is the appropriate way to create a theme or template of some type to avoid repeating these options over different calls to tableGrob? Can I do this with a theme similar to ggplot2 or is a function my best bet?


Solution

  • You could define a new function that sets the fixed parameters to the values you want and only requires you to provide a data frame and column names:

    myTG = function(data.frame, cols = c("Name 1", "Name 2")) {
      tableGrob(data.frame, cols = cols, show.rownames = FALSE, h.even.alpha = 0)
    }
    

    Then to run it:

    tg1 = myTG(df, c("Custom Name 1", "Custom Name 2"))