Search code examples
rr-gridgridextragrob

R tableGrob change format of row


I have some relatively simple code to create a table for printing to a PDF:

library(gridExtra)
df <- head(iris)
tableGrob(df, gp = gpar(fontsize = 8), rows = NULL)

I'd like to make the last row the same format as the header row (bold, and darker gray background). I understand I can use gpar to control format of the entire table, but not sure how to just affect the last row.

Thanks!


Solution

  • One option is to create a new table, and merge the two together,

    g1 <- tableGrob(iris[1:4, 1:3], rows=NULL)
    g2 <- tableGrob(iris[1, 1:3], rows=NULL, # can't have empty content
                    cols=as.character(iris[4, 1:3])) # use 4th row as header
    
    grid.newpage()
    g <- rbind(g1[-nrow(g1), ], g2[1,])
    grid.draw(g)
    

    enter image description here